1

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
4
  • 4
    What have you tried so far?
    – John
    Commented May 4, 2021 at 18:56
  • 2
    Skip every three or just extract unique values? Commented May 4, 2021 at 19:02
  • Skip every three. The above is just an example but I will apply it to my own data.
    – user470057
    Commented May 4, 2021 at 19:10
  • 1
    Of the 4 lines with a in your example, which one do you want (the first, the fourth) or are they identical? Are you perhaps looking for the uniq command?
    – icarus
    Commented May 4, 2021 at 19:17

4 Answers 4

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

5

Using GNU sed:

$ sed -n '1~4p' filename
a
b
c
0
4

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.

1
  • 1
    @EdMorton your comment is now part of answer. Thanks again. Commented May 5, 2021 at 6:43
1

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.

2
  • In second command, three lines are skipped wih 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
  • @PrabhjotSingh 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.
    – Kusalananda
    Commented May 5, 2021 at 7:09

Not the answer you're looking for? Browse other questions tagged .