I want to be able to prepend a string to the beginning of each text file in a folder. How can I do this using bash on Linux?
You can do this as well:
for f in *; do
cat <(echo "someline") $f > tempfile
mv tempfile $f
done
It's not much different from the 1st post but does show how to treat the output of the 'echo' statement as a file without having to create a temporay file to store the value.
A one-liner: rename '' string_ *
This is the easiest I have worked out.
sed -i '1s/^/Text
to add then new file\n/' /file/to/change
And you can do this using sed in 1 single command as well
for f in *; do
sed -i.bak '1i\
foo-bar
' ${f}
done
Here is an example :
for f in *;
do
mv "$f" "whatever_$f"
done
This should do the trick.
FOLDER='path/to/your/folder'
TEXT='Text to prepend'
cd $FOLDER
for i in `ls -1 $FOLDER`; do
CONTENTS=`cat $i`
echo $TEXT > $i # use echo -n if you want the append to be on the same line
echo $CONTENTS >> $i
done
I wouldn't recommending doing this if your files are very big though.