Could anyone help me on arranging the files? I want to skip every three lines based on the example below using awk.
Current file:
a
a
a
a
b
b
b
b
c
c
c
c
Desired output:
a
b
c
$ awk 'NR%4==0 { print $0, "in line#", NR }' infile
a in line# 4
b in line# 8
c in line# 12
so:
awk 'NR%4==0' infile
change to awk 'NR%4==1'
if you want print the first line then skip every next three lines.
Using awk
:
awk '{ print; getline; getline; getline}' file
getline
moves to next line of file. See here. When we do nothing, awk
moves to next line.
In this case three times getline
is used, but no action is given to awk
, so three lines are skipped.
Other use of getline
:
Interestingly getline < "other_file"
command is used for reading a line from other file.
But use of getline
is generally not recommended for this type of problem and is not recommended to be used this way populating builtin variables and without testing for its result, see http://awk.freeshell.org/AllAboutGetline for when and how to use getline
.
Or using awk
with array:
awk '{arr[NR]=$0; }END{ for(i=1;i<=NR;i=i+3) print arr[i]}' file
Here arr indexed on NR(record numbers, i.e. lines) is created in main
block. In END
block a for loop works for us.
Using standard sed
:
sed -n 'N;N;N;P' file
For each line read from file
, this reads an additional three lines and appends them to the original line with delimiting newline characters using N
. The P
command then prints the original line, up to the first newline character.
Alternatively:
sed -n 'p;n;n;n' file
This is similar, but first prints the current line and then reads in three other lines that are discarded.
n
. But in sed 'n;n;n;d' file
three lines are printed before skipping a line with n
.
Commented
May 5, 2021 at 6:58
n
prints the current line and reads the next, so n;n;n;
would print line 1, 2, and 3, then the d
would delete the 4th line read by the last n
. This would then repeat, so you delete every 4th line.
a
in your example, which one do you want (the first, the fourth) or are they identical? Are you perhaps looking for theuniq
command?