Bash Text Processing – How to Append Text to Beginning and End of Multiple Text Files

filesshell-scripttext processing

I have a directory full of text files. My goal is to append text to the beginning and end of all of them. The text that goes at the beginning and end is the same for each file.

Based on code I got from the web, this is the code for appending to the beginning of the file:

echo -e 'var language = {\n$(cat $BASEDIR/Translations/Javascript/*.txt)' > $BASEDIR/Translations/Javascript/*.txt

This is the code for appending to the end of the file. The goal is to add the text }; at the end of each file:

echo "};" >> $BASEDIR/Translations/Javascript/*.txt

The examples I drew from were for acting on individual files. I thought I'd try acting on multiple files using the wildcard, *.txt.

I might be making other mistakes as well. In any case, how do I append text to the beginning and end of multiple files?

Best Answer

To prepend text to a file you can use (with the GNU implementation of sed):

sed -i '1i some string' file

Appending text is as simple as

echo 'Some other string' >> file

The last thing to do is to put that into a loop which iterates over all the files you intend to edit:

for file in *.txt; do
  sed -i '1i Some string' "$file" &&
  echo 'Some other string' >> "$file"
done
Related Question