How do I append text to the beginning and end of multiple text files in Bash?
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
You can use GNU 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 i
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;
:
sed -i -- '/var y = 2;/i//initialize variable y' *.js
Fully POSIX compliant command, using ex
:
for f in *.txt; do printf '%s\n' 0a 'var language = {' . '$a' '};' . x | ex "$f"; done
If you run the printf
portion of the command by itself, you will see the exact editing commands that it is passing to ex
:
0a
var language = {
.
$a
};
.
x
0a
means "Append text after line 0" (in other words, before the first line). The next line is the literal text to "append" after line 0. The period (.
) on a line by itself ends the text to be appended.
$a
means to append text after the last line of the file.
x
means to save the changes and exit.