Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace "\n" with newline in awk

Tags:

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

like image 993
Cotten Avatar asked Jul 04 '14 12:07

Cotten


People also ask

How do you replace N with a new line?

So: Press CTRL-h and the Replace dialog will open. Type \r\n in "Find what" and \\r\\n in "Replace with". Then select search mode Extended (\r, \n, \t, \x..., \0) and click "Replace All".

How do I add a new line in awk?

Original answer:Append printf "\n" at the end of each awk action {} . printf "\n" will print a newline.

How do you convert N to a new line in Python?

Create a string containing line breaksInserting a newline code \n , \r\n into a string will result in a line break at that location. On Unix, including Mac, \n (LF) is often used, and on Windows, \r\n (CR + LF) is often used as a newline code.


1 Answers

How about this?

$ cat file John\nDoe Sara\nConnor  $ awk '{gsub(/\\n/,"\n")}1' file John Doe Sara Connor 
like image 143
Avinash Raj Avatar answered Sep 28 '22 04:09

Avinash Raj