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/$/;%/' %
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 filesfind
doesn't support +
, use ;
insteadfind . -type f
will give list of all files in current directory-exec
allows to use a command to act upon all those filesfind . -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 /
removedAnswered by Sundeep on November 28, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP