Reputation: 5613
I would like to prepend some text to multiple files in bash, I've found this post that deals with prepend: prepend to a file one liner shell?
And I can find all the files I need to process using find:
find ./ -name "somename.txt"
But how do I combine the two using a pipe?
Upvotes: 5
Views: 6373
Reputation: 112424
You've got several options. Easiest is probably sed:
find ./ -name somename.txt -exec sed -e '1i\
My new text here' {} \;
It'll be faster if you add '2q' to tell it you're done after prepanding the text, and if will happen in place in the file with the -i flag:
find ./ -name somename.txt -exec sed -i .bak -e '2q;1i\
My new text here' {} \;
To prepend multiple lines, you'll need to end each one with a backslash.
That leaves the original files around with a .bak
extension.
Upvotes: 9
Reputation: 54111
find . -name "somefiles-*-.txt" -type f | while read line; do sed -i 'iThis text gets prepended' -- "$line"; done
or
find . -name "somefiles-*-.txt" -type f | xargs sed -i 'iGets prepended' --
The best (I think):
find . -name "somefiles-*-.txt" -type f -exec sed -i 'iText that gets prepended (dont remove the i)' -- '{}' \;
Thanks for the missing "-hint. I added the important --s then, too.
Upvotes: 1
Reputation: 182878
find ./ -name "somename.txt" -print0 | xargs -0 -n 1 prepend_stuff_to
Upvotes: -1
Reputation: 6331
find . -name "somename.txt" | while read a; do prepend_stuff_to "$a" ; done
or
find . -name "somename.txt -exec prepend_stuff_to "{}" \;
Upvotes: -1