Why does awk not print newlines?

I have a file that looks like this:

1 2 AA 4 5 AA BB 7 8 AA BB CC 10 11 AA BB CC DD 

I use awk to retrieve only each nth line, where n=3 .

 >>awk 'NR%3==0' /input/file_foo >> output/file_foobar 

The output is displayed in one line as follows:

 AA AA BB AA BB CC AA BB CC DD 

..... etc.

I want it to display as:

 AA AA BB AA BB CC AA BB CC DD 

I tried using \n , printf with \n and so on, but it does not work as I expect. Please inform.

+8
awk
source share
3 answers

Literal way

 awk '{ if (NR%3==0) { print $0} }' 

You can also use {printf("%s\n\n", $0)} too. if single \n does not work.

If it still does not work, you may need to check the line terminator. This may be wrong. Use the RS variable in awk to split on an unusual line terminator.

+8
source share

I think the problem is how you display the data, not the processing.

 $ cat x 1 2 AA 4 5 AA BB 7 8 AA BB CC 10 11 AA BB CC DD $ awk 'NR%3==0' x AA AA BB AA BB CC AA BB CC DD $ 

I suspect what you are doing is like:

 $ awk 'NR%3==0' x > y $ x=$(<y) $ echo $x AA AA BB AA BB CC AA BB CC DD $ echo "$x" AA AA BB AA BB CC AA BB CC DD $ 

It will confuse you. See Also: Capturing multiline output for a bash variable .

+3
source share

For each line, use print following:

 awk 'NR%3==0 { print $0 }' /input/file_foo >> output/file_foobar 
+2
source share

All Articles