20

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?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
therin
  • 1,448
  • 1
  • 15
  • 27

9 Answers9

31

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
drysdam
  • 8,341
  • 1
  • 20
  • 23
  • 9
    Both `$f` should be `"$f"`. It would be good to do some error checking too. Also, it changes permissions and ownership of the original file. – ikegami Apr 26 '11 at 21:38
25

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}' *
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
5

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

This is the easiest I have worked out.

sed -i '1s/^/Text to add then new file\n/' /file/to/change

Taryn
  • 242,637
  • 56
  • 362
  • 405
0

Here is an example :

for f in *; 
do
    mv "$f" "whatever_$f"
done
IK Cheng
  • 11
  • 1
  • 3
0

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.

Cfreak
  • 19,191
  • 6
  • 49
  • 60
0

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.

sashang
  • 11,704
  • 6
  • 44
  • 58
0

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
edgar
  • 1
-1

A one-liner: rename '' string_ *

user151841
  • 17,377
  • 29
  • 109
  • 171