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
Chris Davies
  • 116,213
  • 16
  • 160
  • 287

4 Answers4

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.

αғsнιη
  • 41,407
5

Using GNU sed:

$ sed -n '1~4p' filename
a
b
c
αғsнιη
  • 41,407
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.

Ed Morton
  • 31,617
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.

Kusalananda
  • 333,661
  • 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. – Prabhjot Singh May 05 '21 at 06: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 May 05 '21 at 07:09