bashawk

Replace "\n" with newline in awk


I'm tailing logs and they output \n instead of newlines.

I thought I'd pipe the tail to awk and do a simple replace, however I cannot seem to escape the newline in the regex. Here I'm demonstrating my problem with cat instead of tail:

test.txt:

John\nDoe
Sara\nConnor
cat test.txt | awk -F'\\n' '{ print $1 "\n" $2 }'

Desired output:

John
Doe
Sara
Connor

Actual output:

John\nDoe

Sara\nConnor

So it looks like \\n does not match the \n between the first and last names in test.txt but instead the newline at the end of each line.

It looks like \\n is not the right way of escaping in the terminal right? This way of escaping works fine in e.g. Sublime Text:

regex working in ST3


Solution

  • How about this?

    $ cat file
    John\nDoe
    Sara\nConnor
    
    $ awk '{gsub(/\\n/,"\n")}1' file
    John
    Doe
    Sara
    Connor