Delete \ r \ n in awk

I have a simple awk command that converts a date from MM / DD / YYYY to YYYY / MM / DD. However, the file I'm using has \ r \ n at the end of the lines, and sometimes the date is at the end of the line.

awk '
  BEGIN { FS = OFS = "|" }
  {
    split($27, date, /\//)
    $27 = date[3] "/" date[1] "/" date[2]

    print $0
  }
' file.txt

In this case, if the date MM/DD/YYYY\r\n, then I get this as a result:

YYYY
/MM/DD

What is the best way to get around this? Keep in mind, sometimes input is simple \r\n, in which case the output MUST be //, but instead ends up like

/
/
+4
source share
2 answers

Given that it is \rnot always at the end of the field $27, the easiest way is to remove \rfrom the entire line.

GNU Awk Mawk ( awk Linux), , RS, :

awk -v RS='\r\n' ...

, \r\n - , ORS :

awk 'BEGIN { RS=ORS="\r\n"; ... 

: BSD/macOS Awk:

BSD/macOS awk RS ( POSIX Awk spec: RS , ").

, sub Awk script \r :

awk '{ sub("\r$", ""); ... 

\r\n - , -v ORS='\r\n' ( ORS="\r\n" script BEGIN) , GNU Awk Mawk.

+6

, \n , \r . :

$ awk '{sub(/\r/,"",$NF); ...}'
0

Source: https://habr.com/ru/post/1674427/


All Articles