9

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.

Jacek Laskowski
  • 72,696
  • 27
  • 242
  • 420
mane
  • 2,093
  • 4
  • 16
  • 14

3 Answers3

9

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.

Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
  • Does not seem to work at all. The second one produces some errors. the first one does not print the correct results at all. I actually want to copy every 3rd line in a file to another file, that's all. – mane Feb 28 '12 at 23:01
  • 1
    I think your Files line terminator is not proper. – Shiplu Mokaddim Feb 28 '12 at 23:11
  • Thanks Shiplu. The line terminator was not proper. It works now. – mane Feb 28 '12 at 23:21
3

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.

Community
  • 1
  • 1
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
2

Use the following with print for each line:

awk 'NR%3==0 { print $0 }' /input/file_foo >> output/file_foobar
Jacek Laskowski
  • 72,696
  • 27
  • 242
  • 420
huelbois
  • 6,762
  • 1
  • 19
  • 21