Using Awk To Extract Lines Inwards A Text File

awk is non an obvious selection equally a tool for strictly extracting rows from a text file. It is improve known for its column/field manipulation capabilities inward a text file. More obvious choices are sed, together with perl. You tin run into how sed does it inward my earlier entry.

If y'all opt for awk, y'all tin purpose its NR variable which contains the release of input records together with then far.

Suppose the text file is somefile:
$ truthful cat > somefile.txt
Line 1
Line 2
Line 3
Line 4

To impress a unmarried work number, order work 2:
$ awk 'NR==2' somefile.txt
Line 2


If the text file is huge, y'all tin cheat yesteryear exiting the programme on the offset match. Note that this hack volition non operate if multiple lines are existence extracted.
$ awk 'NR==2 {print;exit}' somefile.txt
Line 2


To extract a department of the text file, order lines ii to 3:
awk 'NR==2,NR==3' somefile.txt
Line 2
Line 3


A to a greater extent than interesting chore is to extract every nth work from a text file. I showed previously how to create it using sed together with perl.

Using awk, to impress every mo work counting from work 0 (first printed work is work 2):
$ awk '0 == NR % 2'  somefile.txt
Line 2
Line 4


To impress every mo work counting from work ane (first printed work is 1):
$ awk '0 == (NR + 1) % 2'  somefile.txt
Line 1
Line 3


% is the modernistic (i.e. remainder) operator.

Berlangganan update artikel terbaru via email:

0 Response to "Using Awk To Extract Lines Inwards A Text File"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel