How do I add the filename to the end of each line in this file?

I need to do the following for hundreds of files: Add the filename (which may contain spaces) to the end of each line in the file.

I think there must be some way to do this:

sed -e 's/$/FILENAME/' *

      

where FILENAME

represents the name of the current file. Is there a sed variable representing the current filename? Or does anyone have another solution using bash, awk, etc.?

0


source to share


7 replies


I'm sure there are other ways to do this, I would use perl:



perl -p -i -e 's/$/$ARGV/;' *

      

+8


source


You can do it with a bash script

for i in * 
do
  sed -e "s/\$/$i/" "$i" 
done

      

Single layer version:



for i in * ; do sed -e "s/\$/$i/" "$i" ; done

      

Edit: If you want to replace the contents of the file with new lines with the appended name, follow these steps:

TFILE=`mktemp`
for i in * 
do
  sed -e "s/\$/$i/" "$i" > $TFILE
  cp -f $TFILE "$i"
done
rm -f $TFILE

      

+4


source


Some sed versions support the "-in-place" argument, so you can configure Tyler's solution to

for i in * ; do 
  sed -e "s/\$/$i/" --in-place "$i" 
done

      

+4


source


awk '{print $0,FILENAME}' > tmpfile

      

+2


source


In BASH, I would do something that:

for f in *; do echo $f >> $f; done

      

0


source


More or less, as Tyler suggested, just with some changes to allow for spaces in the name. I was hoping for one liner though ...

(
  OLDIFS=$IFS
  IFS=$'\n'
  for f in *
  do
    IFS=OLDIFS
    sed -e "s/\$/$f/" $f > tmpfile
    mv tmpfile $f
    IFS=$'\n'
  done
)

      

0


source


This might work for you:

printf "%s\n" * | sed 's/.*/sed -i "s|$| &|" &/' | bash

      

0


source







All Articles