How to prepend a line to all files in a directory?

Using GNU sed:

for sql in backup/*.sql; do
    sed -i '1i\use my_db;' "$sql"
done

With standard sed:

for sql in backup/*.sql; do
    sed '1i\
use my_db;
' "$sql" >"$sql.bak" && mv "$sql.bak" "$sql"
done

This would do a in-place editing of each .sql file in backup. The editing command inserts a line before the first line in each file.

This assumes that the pattern backup/*.sql only matches the files that you want to edit.


Using echo and cat:

for sql in backup/*.sql; do
    { echo 'use my_db;'; cat "$sql"; } >"$sql.tmp" && mv "$sql.tmp" "$sql"
done

In this loop, we first output the line that we'd like to prepend to the file, then the contents of the file. This goes into a temporary file which is then renamed.


The command

echo 'use my_db;' >> backup/*.sql

would expand to something like

echo 'use my_db;' >> backup/file1.sql backup/file2.sql backup/file3.sql

which is the same as

echo 'use my_db;' backup/file2.sql backup/file3.sql >> backup/file1.sql

which would append the given strings to backup/file1.sql.

Your second command would not modify any files.


Solution

sed -i '1 i\use my_db' backup/*.sql

Explanation

sed -i Keep the changes in the files, do not write them to stdout.

1 - When sed is positioned on the first line.

i - Insert the following line.

backup/*.sql Files on which sed will perform.

Tags:

Printf

Sed