Search code examples
sedcarriage-return

Bash: Append text in-line with ^M-polluted strings


The focus of this question shifted a bit, the real problem is addressed in Edit 2 below. The problem at the start:

I want to append a simple string, for example the letter N, to all lines in my file. This must happen without introducing linebreaks. What I need looks like this:

file     result
Aa       AaN
Bb       BbN
C        CN
Dd       DdN

The only thing I found so far is

sed -e 's/../&N/'

which appends the string only at a certain location, so for entries with varying character length this does not work as the result looks like this:

AaN
BbN
C
N
DdN

The most simple analogon is

sed -e 's/^/&N/' file

which prepends each line. So I need the reverse parameter of ^ that allows me to append to each line, no matter how long the string is in that line. The other questions I found about appending introduce several other constraints that don't apply here.


Edit: The suggested

sed 's/$/N/' file > file2

only changes the very last line in my file., whereas I need the change in every line. It seems to work in the linked question but here it does not. I don't know why.


Edit 2:

As RavinderSingh13 pointed out, my list that I obtained by some other commands contained ^M characters. So by using

cat -v file

the real content was revealed:

Aa^M
Bb^M
C^M
Dd^M

The presented solution was able to fix this issue!


Solution

  • If you are ok with awk, you could simply use print instead of substitution too.

    awk '{gsub(/\r/,"");print $0"N"}'  Input_file
    

    In case you want to do for a specific field vice then try:(taking example where 1st field should be append with N here):

    awk '{gsub(/\r/,"");$1=$1"N"} 1'  Input_file