for example file1 contains:

entry1:value1
entry2:value2
entry3:value3

now I want to add a prefix "file1:" to each line:

file1:entry1:value1
file1:entry2:value2
file1:entry3:value3

How can I do that in one command line?

I'm using bash.
BTW, The leading space must be preserved, so bash built-in read line doesn't work for me.

link|improve this question

At last, I decided to write a small C program. All command-line utilities seem have a limitation when PREFIX/SUFFIX contains special chars. – Xie Jilei Aug 10 '11 at 0:53
feedback

5 Answers

up vote 5 down vote accepted
% sed 's/^/file1:/' file1
link|improve this answer
The only problem of sed is, how to escape my prefix if it contains special chars? – Xie Jilei Jul 12 '10 at 13:07
2  
that is not a problem of 'sed' but of your quoting skills :) – akira Jul 12 '10 at 13:14
Well, the prefix/suffix is variable indeed, it's not easy to quote all special chars, and even I can quote them all, the script maybe not portable at all. – Xie Jilei Aug 10 '11 at 0:50
feedback

read splits by $IFS, so you have to clear that first.

while IFS= read line
do
  echo "file1:$line"
done
link|improve this answer
feedback

awk equivalent of the sed answer

awk '{gsub(/^/,"file1:")}1' file

or just simply

awk '{$0="file:1"$0}1' file
link|improve this answer
feedback

Escaping special characters:

printf -v prefix %q 'ab\cd%;,: /{][}-+*'; prefix=${prefix////\\/}; sed "s/^/$prefix/" file
link|improve this answer
feedback

I using AWK, you can add pretty much any prefix:

awk -v PRE='anything:' '{$0=PRE$0; print}' file1

This will work even for fancy non-printable chars.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.