I have a file say abc.txt with following data (real data has many records,say around 200)

Sno | Name
1 | Jack
2 | Jill
3 | June

Now how do I append text to make my file look like this,

Sno | Name | Place
1 | Jack | Paris
2 | Jill | Paris
3 | June | Paris

I tried replacing globally ,but first line should be appended with different text.So please help me out guys.


Here are three options:

  • awk and its variants (gawk, mawk etc.):

    awk '{if(NR==1){print $0,"| Place"} else{print $0,"| Paris"}}' file.txt
  • Perl:

    perl -lne '$.==1 ? print "$_ | Place" : print "$_ | Paris"' file.txt
  • sed

    sed '1 s/$/ | Place/; 1! s/$/ | Paris/' file.txt 
  • Note that it's not only gawk or mawk, it's any awk implementation, POSIX ones, and even the original awk from 1981 Sep 2 '13 at 13:50
  • @StephaneChazelas fair enough, that's why following your edit I used awk in the example and (g/m)awk in the header. Thanks.
    – terdon
    Sep 2 '13 at 13:51
  • 1
    @StephaneChazelas why is 1! better than 2,$? Is it just because it is shorter or is there a difference in the implementation?
    – terdon
    Sep 2 '13 at 13:53
  • 1
    IMO, shorter and easier to understand: you want the first substitution on the first line, and the second substitution on anything but the first line. Feel free to revert. I agree that edit was a bit cavalier, sorry. Sep 2 '13 at 13:56
  • 3
    @StephaneChazelas not cavalier, the day you make a mistaken correction I will be (extremely) happy to point it out, till then I am just trying to learn and begin with the assumption that you're right. Thanks for explaining.
    – terdon
    Sep 2 '13 at 13:58

For scripted "in-place" file editing, use ex:

printf '%s\n' '1s/$/ | Place/' '2,$s/$/ | Paris/' x | ex abc.txt
  • printf gives the commands to ex.
  • 1s performs the substitute on the first line only.
  • 2,$s performs the substitution on all other lines.
  • x saves and exits.

The $ in the regex means "end of line."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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