ahaswer
ahaswer

Reputation: 55

Select specific lines with awk but not range

I would like to select lines from file. I'm interested in three specific lines.

Input:

line1
line2
line3
line4
line5
line6
line7

Output:

line2
line3
line7

There is no specific pattern of selecting lines. I'm familiar with sed solution:

sed -n '2p; 3p; 7p' file

However I'm using awk to select specific fields of those lines afterwards. Therefore I would prefer to use awk alone instead of piping sed and awk. Still I cannot find simple solution with awk.

Upvotes: 1

Views: 148

Answers (4)

Ed Morton
Ed Morton

Reputation: 203219

$ awk 'BEGIN{split("2 3 7",tmp); for (i in tmp) nrs[tmp[i]]} NR in nrs' file
line2
line3
line7

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163207

Using a character class to match 2 3 or 7 and FNR to match the record number of the current file:

awk 'FNR ~ /^[237]$/' file

Output

line2
line3
line7

If you have a large file and yo u know the maximum line you can also stop processing when you reach it:

awk 'FNR ~ /^[237]$/{
  print
  if (FNR == 7) exit
}' file

Upvotes: 0

Daweo
Daweo

Reputation: 36370

I would harness GNU AWK for this task following way, let file.txt content be

line1
line2
line3
line4
line5
line6
line7

then

awk 'BEGIN{a[2]=a[3]=a[7]=1}(NR in a){print}' file.txt

output

line2
line3
line7

Explanation: I use array a where I set value for keys 2 and 3 and 7. If current number row (NR) is one of keys set I print said line.

(tested in gawk 4.2.1)

Upvotes: 2

Kaffe Myers
Kaffe Myers

Reputation: 464

awk 'FNR ~ /^(2|3|7)$/{print}'

Should do the trick quite neatly

Upvotes: 2

Related Questions