How append a string at the end of all lines?

31,146

Solution 1

\x0D is carriage return, which may or may not be visible in your text editor. So if you've edited the file in both Windows and a Unix/Linux system there may be a mix of newlines. If you want to remove carriage returns reliably you should use dos2unix. If you really want to add text to the end of the line just use sed -i "s|$|--end|" file.txt.

Solution 2

There are may ways of doing this:

  1. Perl

    perl -i -pe 's/$/--end/' file.txt
    
  2. sed

    sed -i 's/$/--end/' file.txt
    
  3. awk

    awk '{$NF=$NF"--end"; print}' file.txt > foo && mv foo file.txt
    
  4. shell

    while IFS= read -r l; do 
     echo "$l""--end"; 
    done < file.txt > foo && mv foo file.txt
    
Share:
31,146

Related videos on Youtube

rkifo
Author by

rkifo

Updated on September 18, 2022

Comments

  • rkifo
    rkifo over 1 year

    I'm trying to add a string at the end of all lines in a text file, but I have a mistake somewhere.

    Example:

    I've this in a text file:

    begin--fr.a2dfp.net
    begin--m.fr.a2dfp.net
    begin--mfr.a2dfp.net
    begin--ad.a8.net
    begin--asy.a8ww.net
    begin--abcstats.com
    ...
    

    I run:

    sed -i "s|\x0D$|--end|" file.txt
    

    And I get:

    begin--fr.a2dfp.net--end
    begin--m.fr.a2dfp.net--end
    begin--mfr.a2dfp.net--end
    begin--ad.a8.net
    begin--asy.a8ww.net--end
    begin--abcstats.com
    ...
    

    The string is added only in certain lines and not in others.

    Any idea why?

  • rkifo
    rkifo over 10 years
    Yes, it's a text file from Windows edited in Linux. dos2unix really solve problem and now, add --end at the end of all my lines. Thank You!!!!
  • terdon
    terdon over 10 years
    @user294721 if this answer solves your problem, please remember to mrk it as accepted.
  • glenn jackman
    glenn jackman over 10 years
    you can remove the carriage returns in the same sed: sed 's/\r\?$/--end/'
  • terdon
    terdon over 10 years
    @user294721 you're very welcome. Please remember to accept one of these answers so the question can be marked as answered.