Inserting filename at the top of file

Hi Forum members,

I want to insert the filename at the top of file (i.e, first row only)

My file name is like

 asdf_432

And I want to insert this filename in first row as

filename is asdf with serial no. 432 

Thanks in advance. :slight_smile:

#! /bin/bash

f="asdf_432"
x=${f%_*}
y=${f#*_}

sed -i.bak "1i filename is $x serial no. $y" $f
1 Like

Try also:

$ echo filename is ${f%_*} serial no. ${f#*_} | cat - $f
1 Like

Code given above are working well, but what if the filename consists of more than 1 underscore. And I want to apply this condition on last underscore. i.e, my filename is like:

asdf_01_1234

And I need to print :

Filename is asdf_01 with serial no. 1234

at the top of the file.

Thanks in advance.

Hey, come on, be reasonable, and be creative. If you want to print "with", embed "with" into the text.
And, for "last underscore", man bash:

1 Like