I have a file beginning.txt that contains lines like:
Disclaimer Here
This is a Notice
I have something liere
How can I execute a linux command to add all the lines in beginning.txt to the top of each file that matches the extension ".customfile" (note that .customfile is just a textfile, but these files may be within subdirectories within my current folder that i also want updated)?
I have many files with the .customfile suffix that I want to append, so looking for a way to do this programatically. I see example with sed command that appear limited to a single line.
sed -i '1s/^/<added text> /' file
With bash:
for file in $(find . -name "*.customfile"); do
echo Processing $file
cat beginning.txt $file > $file.modified
mv $file.modified $file
done
The sed
command r
is pretty useful in appending contents of a file at certain location, except when that location is line 0.
Inserting your text before line 1 is like appending after line 0. It would've been the solution if sed '0r /path/to/beginning.txt *.customfile
was allowed.
You can use process substitution along with sed
. The process substitution will generate a sed
command that can be run against any files you searched for.
sed -i -f - file < <(sed 's/^/1i/' /path/to/beginning.txt)
The process sed 's/^/1i/' /path/to/beginning.txt
will generate sed
commands to insert the texts found in /path/to/beginning.txt
:
1iDisclaimer Here
1iThis is a Notice
1iI have something liere
sed -f -
will read the sed command from a file, -
means the file is stdin
.
If you need to run it on multiple files, you can either use globs or find
and xargs
.
Sample using multiple files:
sed -i -f - /path/to/*.customfile < <(sed 's/^/1i/' /path/to/beginning.txt)
Sample using find and xargs:
find . -type f -name \*.customfile | xargs -I{} bash -c "sed -f - {} < <(sed 's/^/1i/' /tmp/beginning.txt)"
Alternatively, you can avoid re-running sed 's/^/1i/' /path/to/beginning.txt
for every file by assigning the output to a variable and using here string to pass to the sed
command.
sedcommand=$(sed 's/^/1i/' /path/to/beginning.txt)
sed -i -f - /path/to/*.customfile <<< "$sedcommand"
Or create a command.sed
file from beginning.txt
and use it to insert the texts to your custom files.
sed 's/^/1i/' /path/to/beginning.txt > /path/to/command.sed
sed -i -f /path/to/command.sed /path/to/*.customfile
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With