Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is awk not printing out newlines?

Tags:

awk

I have a file which looks like this:

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

I am using awk to extract only every nth line where n=3.

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

The output is appearing in a single line as:

AA AA BB AA BB CC AA BB CC DD

.....and so on

I want it to appear as:

AA 
AA BB 
AA BB CC 
AA BB CC DD 

I tried using \n, printf with \n, and so on but it doesn't work as I expect. Please advise.

like image 459
mane Avatar asked Feb 28 '12 22:02

mane


People also ask

Is awk '{ print $2?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output. xargs kill -${2:-'TERM'} takes the process IDs from the selected sidekiq processes and feeds them as arguments to a kill command.

What is awk '{ print $4 }'?

'{print $4}' means print the fourth field (the fields being separated by : ).

What is awk '{ print $1 }'?

awk treats tab or whitespace for file separator by default. Awk actually uses some variables for each data field found. $0 for whole line. $1 for first field. $2 for second field.

How do I print blank lines in awk?

For blank lines this is zero. The default awk action is to print lines for which the pattern is true. Here the pattern is NF. Zero is interpreted as false and so nothing is printed.


2 Answers

A verbose way,

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

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

If it still does not work you might need to check the line terminator. It may not be proper. Use the RS variable in awk to separate on the unusual line terminator.

like image 122
Shiplu Mokaddim Avatar answered Sep 22 '22 00:09

Shiplu Mokaddim


I think the problem is in the way you're showing the data, not in 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 that what you're doing is similar to:

$ 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
$

This would confuse you. See also: Capturing multi-line output to a bash variable.

like image 21
Jonathan Leffler Avatar answered Sep 21 '22 00:09

Jonathan Leffler