Mayank Tripathi
Mayank Tripathi

Reputation: 523

How to handle different line end such as lines end with CRLF (\r\n) and line end with LF (\n) or CR (\r) in AWK

I am new to AWK, and the requirement is to split one of the field and append it to end of record / row, for this I am using awk command which I shared below. However when the file is having different end of line such as CR or CRLF it is behaving differently.

awk command :

awk 'BEGIN { FS = "~" }; {fullname=$1}; {split(fullname, a, " ")}; { if (fullname=="TT") newmodifiedline=$0; else newmodifiedline=$0"~"a[1]"~"a[2]; }; { print newmodifiedline }' example.txt > example_modified.txt

When the example.txt file has CRLF as the end of line as below enter image description here

The result will be where the appended fields is moved to next line. Which is not expected. enter image description here

However when using the file with end of line is LF, I do get desired result and the appended values are correctly appended at the end of record as below. enter image description here

Is there a way I could handle it irrespective of end-of-line character or set the end-of-line char to LR and then run the awk command? Please help.

Upvotes: 0

Views: 966

Answers (1)

Ed Morton
Ed Morton

Reputation: 204099

awk '
{ sub(/\r$/,"") }
...other stuff...
' file

is probably what you want, otherwise see Why does my tool output overwrite itself and how do I fix it?

Upvotes: 3

Related Questions