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.
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.
'{print $4}' means print the fourth field (the fields being separated by : ).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With