Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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.

share|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. –  Xiè Jìléi Aug 10 '11 at 0:53

7 Answers 7

up vote 5 down vote accepted
% sed 's/^/file1:/' file1
share|improve this answer
    
The only problem of sed is, how to escape my prefix if it contains special chars? –  Xiè Jìléi 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. –  Xiè Jìléi Aug 10 '11 at 0:50

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.

share|improve this answer

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

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

Escaping special characters:

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

awk equivalent of the sed answer

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

or just simply

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

Perl can handle this with no particular difficulty. I am testing them with the variable $foo which contains every weird character I can think of including the carriage return, space etc:

$ foo=$(echo -e "\r'{}[]- \`~^&%$=@\!#\"")
$ echo $foo | od -c
0000000  \r   '   {   }   [   ]   -       `   ~   ^   &   %   $   =   @
0000020   \   !   #   "  \n
0000025
$ export foo

So, to add these to the beginning and end of each line of file bar.txt:

perl -ne 'chomp; print "$ENV{foo}:$_:$ENV{foo}\n"' bar.txt

The %ENV hash contains the user's environment variables (which is why I export $foo above). The special variable $_ contains the current line and chomp removes the trailing new line from it:

share|improve this answer

The most readable and easy to remember one for me to add both prefix and suffix is the following:

$ echo "  foo bar  " | awk '{print "--"$0"++"}'

which outputs

  --  foo bar  ++

Note the whole input including leading/trailing spaces is preserved.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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