More Shell Scripting Fun

Here is another thing I encountered just now… when you use cat to read the contents of a file into a bash variable, it tends to lose its formatting with out a really good way to preserve that formatting. To preserve the formatting from a catted file inside a bash variable use the following:

VAR=$(/bin/cat -E /path/to/file/filename.txt)

The -E option for cat will place $ for each end of line, then use this to convert them to something we can use:

NEWVAR=$(echo $VAR | sed ‘s/$ /\\n/g’)

This will replace the $ and the [space] that follows it with \n, then we use echo’s -e option to convert the \n’s to line feeds.

echo -e $NEWVAR > /path/to/file/newfilename.txt)

There is another option for cat (-A) that outputs newlines as $ and tabs as ^I, however I am unable to pattern match the ^I because I can’t figure out the key combo to make a match to it. (CTRL+V then CTRL+I and CTRL+V then TAB do not produce a ^I).

Comments (0)

› No comments yet.

Pingbacks (0)

› No pingbacks yet.