Sed remove characters from new line

sed

After some processing, I have my input file like below.

file1.txt

12345|john|student
43321|jack|professor

78965|alex|lecturer

I need to process the above file further and so I need a line breaker at the end of the line too. Currently, I can accomplish it as below.

sed 's/$/|/' file1.txt

The above command results in the output as,

12345|john|student|
43321|jack|professor|
|
78965|alex|lecturer|

As we can see, the | is appended to blank lines too. When I tried to remove the | character again from blank lines using below command,

sed 's/|//g' file1.txt

The | character is getting deleted everywhere. How can I delete only the | in blank lines? I need to keep the blank line also.

Best Answer

From your original, you can add | to lines that is not blank:

Using sed:

sed -e '/^$/!s/$/|/' file

Using perl:

perl -lpe 's/$/|/ if length' file

If you want to remove | from lines that is blank (in second version):

perl -lpe 's/\|// if length == 1'
Related Question