TransWikia.com

How to add filename to end of every line - all files in all subdirectories

Unix & Linux Asked on November 28, 2021

I want to add a line to my bash script (ubuntu 16) to add the filename to the end of every line in a file – that is every file in a folder and all files in all subfolders.

Filenames are alphanumeric with some special characters like -_.

For example:

Line in file filename_ghrut.txt before:

blah blah blah
blahblah blahblah

Line in file filename_ghrut.txt after:

blah blah blah filename_ghrut.txt
blahblah blahblah filename_ghrut.txt

I have searched around but most commands don’t seem to work.

I want to run this on all files in all subfolders of a specific directory.

Big thanks.

I found this, but it doesn’t quite work:

ls file{1..5}.txt|xargs -I% sed -i 's/$/;%/' %

3 Answers

With GNU awk:

LC_ALL=C find . -type f -exec gawk -i inplace '
  BEGINFILE {suffix = FILENAME; sub(/.*//, "", suffix)}
  {print $0, suffix}' {} +

Beware that if there are several hard links of the same file, the name for each will be added (in no particular order) to each line of that file.

Answered by Stéphane Chazelas on November 28, 2021

Try this, using find and sed:

find /path/to/top_directory -type f -execdir sed -i -e "s/$/ {}/" {} ;

Replace /path/to/top_directory with the directory where the files you want to edit are.

Answered by thiagowfx on November 28, 2021

With perl and find

find . -type f -exec perl -i -pe 's/$/ $ARGV/' {} +
  • s/$/ $ARGV/ add space and filename to end of each line
  • -i for inplace editing, use i.bkp if you want to retain a backup of original files
  • If your find doesn't support +, use ; instead
  • find . -type f will give list of all files in current directory
  • -exec allows to use a command to act upon all those files
  • Use find . -type f -name '*.txt' if you want to restrict to only files ending with .txt


Thanks @thiagowfx for pointing that above solution will add filename as ./file.txt, ./foo/file2.txt, etc

Use this to add only filename without any ./ etc

find . -type f -exec perl -i -pe 's/$/$ARGV=~s|.*/| |r/e' {} +
  • $ARGV=~s|.*/| |r will give filename with all characters upto / removed

Answered by Sundeep on November 28, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP