Text Manipulation

Convert String to Clean Title


# Does not escape shell characters.
string="_-sOm3-=mE5Sy=+s7r1nG-_"

# Convert numbers to letters.
echo "$string" | tr "0-9" "OIZEASbTBg" |
    # Convert to lowercase.
    tr "[:upper:]" "[:lower:]" |
    # Swap non-alphanumeric for single space.
    tr -cs "[:alnum:]" ' ' |
    # Remove leading/trailing whitespace.
    awk '{$1=$1};1' |
    # Capitalise first letter of each token.
    sed 's/^./\U&/g; s/ ./\U&/g'

Create Fixed Length String of Characters


leng=32
char='A'

head -c "$leng" </dev/zero | tr '\0' "$char"

Cut Last Field


# Reverse line, cut first field, reverse again.
echo "only want last field" | rev | cut -d' ' -f1 | rev

Delete Line Containing String


sed -i '/pattern to match/d' ./infile

# Create a backup of original file.
sed -i.bak '/pattern to match/d' ./infile

Grep Multiple Strings


grep -E 'this|that|other'

Prepend Text to Start of File


sed -i "1 s/^/prepend-this-text\n/" to-this-file

Strip Non-Printable Characters


string='\tx\ry\nz'

# -d: delete
# -c: complement of
# '[[:print:]]': all printable characters
echo -e "$string" | tr -dc '[[:print:]]'