Marjer
Marjer

Reputation: 1403

Search for a value in a file and remove subsequent lines

I'm developing a shell script but I am stuck with the below part.

I have the file sample.txt:

S.No    Sub1    Sub2
1       100     200
2       100     200
3       100     200
4       100     200
5       100     200
6       100     200
7       100     200

I want to search the S.No column in sample.txt. For example if I'm searching the value 5 I need the rows up to 5 only I don't want the rows after the value of in S.NO is larger than 5.

the output must look like, output.txt

S.No    Sub1    Sub2
1       100     200
2       100     200
3       100     200
4       100     200
5       100     200

Upvotes: 1

Views: 90

Answers (5)

Sidharth C. Nadhan
Sidharth C. Nadhan

Reputation: 2253

sed '6q' sample.txt > output.txt

Upvotes: 0

Eran Ben-Natan
Eran Ben-Natan

Reputation: 2615

The suggested awk relies on that column 1 is numeric sorted. A generic awk that fulfills the question title would be:

gawk -v p=5 '$1==p {print; exit} {print}' 

However, in this situation, sed is better IMO. Use -i to modify the input file.

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246807

And the sed solution

n=5
sed "/^$n[[:space:]]/q" filename

The sed q command exits after printing the current line

Upvotes: 1

jaypal singh
jaypal singh

Reputation: 77105

Using perl:

perl -ane 'print if $F[$1]<=5' file

Upvotes: 1

Chris Seymour
Chris Seymour

Reputation: 85785

Print the first line and any other line where the first field is less than or equal to 5:

$ awk 'NR==1||$1<=5' file
S.No    Sub1    Sub2
1       100     200
2       100     200
3       100     200
4       100     200
5       100     200

Upvotes: 4

Related Questions