Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

4 Answers 4

up vote 11 down vote accepted

To prepend text to a file you can use

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"
share|improve this answer

You can use sed

Like already illustrated, you can insert lines of text right before and after matching lines of a file with sed, using the i and a command respectively. What hasn't been shown is that you can do it with a one-liner and for multiple files at once.

The following will insert a line before the first (1i) and after the last line ($a). The insertions will be executed for all files matching the glob *.txt.

sed -i -e '1ivar language = \{' -e '$a\}\;' *.txt

Both ì and a do not only work with line numbers, but also on every line that matches a given pattern. This would insert a comment whenever a line contains 'var y = 2;' (I think..):

sed -i '/var y = 2\;/i\/\/initialize variable y' *.js

Maybe those could be written less indecipherable, because "#inew text" is the same as "# i\new text".

share|improve this answer

Here's a way to do it in Perl:

for f in *txt; do
  perl -lpe 'BEGIN{print "First string"}END{print "Last string"}' a.txt > foo && 
  mv foo "$f";
share|improve this answer

Also has the right to be (with results in .out files):

find . -name '*.txt' -exec sh -c (echo HEAD;cat {};echo FOOT) > {}.out' \;

Another, more elaborated variant - source files replaced with result:

find . -name '*.txt' -exec sh -c (echo HEAD;cat {};echo FOOT) > {}.tmp && mv {}.tmp {}' \; -print
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.