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?
This will do that. You could make it more efficient if you are doing the same text to each file...
for f in *; do
echo "whatever" > tmpfile
cat $f >> tmpfile
mv tmpfile $f
done
You may use the ed command to do without temporary files if you like:
for file in *; do
(test ! -f "${file}" || test ! -w "${file}") && continue # sort out non-files and non-writable files
if test -s "${file}" && ! grep -Iqs '.*' "${file}"; then continue; fi # sort out binary files
printf '\n%s\n\n' "FILE: ${file}"
# cf. http://wiki.bash-hackers.org/howto/edit-ed
printf '%s\n' H 0a "foobar" . ',p' q | ed -s "${file}" # dry run (just prints to stdout)
#printf '%s\n' H 0a "foobar" . wq | ed -s "${file}" # in-place file edit without any backup
done | less
You can do it like this without a loop and cat
sed -i '1i whatever' *
if you want to back up your files, use -i.bak
Or using awk
awk 'FNR==1{$0="whatever\n"$0;}{print $0>FILENAME}' *