Add filename to a text file

How to add a filename to each line of a text flie with bash shell ?  Tks
AXISHKAsked:
Who is Participating?
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.

woolmilkporcCommented:
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.

FILENAME="filename.txt"
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:

FILENAME="filename.txt"
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 "filename.txt.new" containing the changes.
1
AXISHKAuthor Commented:
Is there any workaround solution to keep the orginal file and only add the column to the new file name ?
0
woolmilkporcCommented:
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:

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

2) Choose a completely new name:

FILENAME="filename.txt"
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.
0

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:
Tks
0
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
Linux

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.