JM88
JM88

Reputation: 477

Add the name of the file as header in a text file

Is there a simple way to add the name of a file as a header in that file?

For example

file.txt contains:

blablabla
blablabla

Desired output:

file.txt
blablabla
blablabla

Upvotes: 0

Views: 347

Answers (4)

Mark Setchell
Mark Setchell

Reputation: 207650

If you really want a one-liner...

perl -pi -E 'say "file.txt" if $.==1' file.txt 

Upvotes: 0

Alfalfa
Alfalfa

Reputation: 131

Here's a one-liner which will run very quickly even with huge files and is easily used to automate this process for an entire directory.

x="$(basename test.txt)" && sed -i "1i$x" $x

You can use the filename directly (text.txt in this case) or use a variable in a loop to go through an entire directory.

Upvotes: 2

sat
sat

Reputation: 14949

You can use sed also,

sed -i "1iyourfile.txt" yourfile.txt

Example:

$ F="yourfile.txt"
$ sed -i "1i$F" $F

Upvotes: 0

Barmar
Barmar

Reputation: 781592

(echo filename; cat filename) > filename.new
mv filename.new filename

Upvotes: 2

Related Questions