How can I append the name of a file to end of each line in that file?

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

It seems to me there should 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 a different solution using bash, awk, etc.?

Answers


I'm sure there are other ways to do it, I'd use perl:

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

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

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

You could do it with a bash script

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

One-liner version:

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

Edit: If you want to replace the contents of the file with the new, name-appended lines, do this:

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

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

In BASH, I'd do something to the effect of:

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

More or less how Tyler suggested, just with some modifications to allow for spaces in the name. I was hoping for a 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
)

This might work for you:

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

Need Your Help

HTTP Status 400: The requested resource is not available

javascript java jquery jsp spring-boot

Can you help me on this one please, I am encountering HTTP Status 400: The requested resource is not available everytime I click my button EDIT and DELETE and I can't fix this for weeks now, could

How do I calculate the time difference in a Django template

django django-templates django-filter

I have a model with two TimeFields. I want to show the time difference in a template (ie, 27 minutes). I see the filter timesince, but it isn't working; I think it only accepts datetimes but my mod...