1

How can I add ",1" at the end of each of the lines using sed? The file I am using is like this;

A
B
C

I tried this;

sed 's/$/,1/' alphabets.txt > alphabets1.txt

and got this;

A
,1
B
,1
C
,1

but what I want is this;

A,1
B,1
C,1

When I tried the best answer from "https://stackoverflow.com/questions/15978504/add-text-at-the-end-of-each-line", I got a blank page.

sed -n 's/$/,1/' alphabets.txt > alphabets2.txt

I found out that there's ^M at the end using cat -vt file. How can I delete it and change it to ",1"?

sarah
  • 49
  • 5

1 Answers1

2

Mac sed is BSD sed. You may try this command on a file optionally ending with \r to remove \r and append 1 in the end:

sed -E $'s/\\\r?$/,1/'

A,1
B,1
C,1

Make sure you shell is bash while running this.

You may also use:

sed -E 's/'$'\r''?$/,1/' file

$'\r' is a BASH string to match \r and ? after this makes it optional.

Please note that this sed command will also run fine on gnu sed.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 2
    You are a genius!!! Thank you so much for your amazing answer, it has worked, and you have saved my day!!! Thank you again!! – sarah Mar 11 '21 at 00:14