8

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 the Bash built-in read line doesn't work for me.

1
  • At last, I decided to write a small C program. All command-line utilities seem have a limitation when PREFIX/SUFFIX contains special chars.
    – Lenik
    Aug 10, 2011 at 0:53

7 Answers 7

10
% sed 's/^/file1:/' file1
3
  • The only problem of sed is, how to escape my prefix if it contains special chars?
    – Lenik
    Jul 12, 2010 at 13:07
  • 2
    that is not a problem of 'sed' but of your quoting skills :)
    – akira
    Jul 12, 2010 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.
    – Lenik
    Aug 10, 2011 at 0:50
2

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.

2
  • Thank you! This really is the easiest way compared to all the other answers and does and both prefix and suffix as an example. Perhaps replace echo with cat filename
    – ooxi
    Sep 29, 2014 at 9:53
  • Thank you. I thought this was very easy to do as someone pretty new to Bash
    – Cameron
    Jan 17, 2018 at 21:13
2

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.

1

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

while IFS= read line
do
  echo "file1:$line"
done
1

Escaping special characters:

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

AWK equivalent of the sed answer:

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

Or just simply:

awk '{$0="file:1"$0}1' file
0

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:

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .