Vivek Sharma
Vivek Sharma

Reputation: 31

How to print File name in the same file?

I have a file with around 5 lines and I want to have the file name printed at the end of every line.

for file in *.txt
do
  sed -i "1s/\$/${file%%.*}/" "$file"
done

The above code only writes file name in first line, I want to have file name in every line.

Upvotes: 1

Views: 168

Answers (2)

axiac
axiac

Reputation: 72226

The above code only writes file name in first line

This is what the 1 on the beginning of the sed command does: it is an address that selects the lines processed by the command.

In your case, the s command applies only to the first line (because of 1 in front of the command). Remove the 1 from the command and it will apply to all lines of the file:

for file in *.txt
do
  sed -i "s/\$/${file%%.*}/" "$file"
done

Read more about sed at https://www.gnu.org/software/sed/manual/sed.html.
Given that you have already learned sed, typing man sed on your terminal will refresh your memory about its commands.

Upvotes: 1

ypnos
ypnos

Reputation: 52357

This is a bit hacky, but it does the trick (bash):

filename=<filename>; len=$(wc -l $filename | cut -f1 -d' '); for i in $(seq $len); do echo $filename; done | paste $filename -

And this is cleaner, but needs python installed:

python -c "import sys; print('\n'.join(line.rstrip() + '\t' + sys.argv[1] for line in open(sys.argv[1])))" <filename>

Upvotes: 0

Related Questions