Add filename to a text file

How to add a filename to each line of a text flie with bash shell ?  Tks
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

I assume that you want to add the filename of the input file at the beginning of each line.
Here I'll use "sed" to achieve this. "awk" or "Perl" etc. could do it as well.

sed -i.bak "s/^/$FILENAME /" $FILENAME

The above will save an unchanged backup file "filename.txt.bak" before applying the changes to "filename.txt"

The anchor "^" (caret) matches the position before the first character in the line (zero-length match).
Please note that a space is added after the filename for readability. You can of course omit it or use any other separator character(s).

If you really want a pure "bash" solution without using any external tools try this:

while read line; do echo "$FILENAME" $line; done < $FILENAME > ${FILENAME}.new

We cannot change "in place" with this method, so we create a new file "" containing the changes.
AXISHKAuthor Commented:
Is there any workaround solution to keep the orginal file and only add the column to the new file name ?
Using the "sed" solution simply omit "-i.bak" and redirect the output of "sed" to the new file:

1) Append ".new" to the original filename:

sed "s/^/$FILENAME /" $FILENAME > ${FILENAME}.new

2) Choose a completely new name:

sed "s/^/$FILENAME /" $FILENAME > name_of_my_new_modified_file.txt

The second "bash only" solution always keeps the original file and creates a new one.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
AXISHKAuthor Commented:
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.