51k
51k

Reputation: 1443

Use '\n' as a field separator in awk command

I have multiple lines, and i need to select one of them, i have found the required lines using grep, but now i want only the first line from the result. How can i do it using, grep, awk, sed etc..

This is first line.
This is second line.
This is seventh line.

Using grep i got the o/p grep "This is s" file.txt.

This is second line.
This is seventh line.

now i need the first line from this. How can i use '\n' as a field separator.

Upvotes: 0

Views: 394

Answers (1)

Chris Seymour
Chris Seymour

Reputation: 85865

Print the first line that matches This is s and quit with awk:

$ awk '/This is s/{print $0; exit}'
This is second line.

However GNU grep has the -m option which stops are the given number of matches:

$ grep -Fm 1 'This is s' file
This is second line.

Note: the -F is for fixed string matching instead of regular expressions.

And for completeness with sed you could do:

$ sed '/This is s/!d;q' file
This is second line.

However the example seems slightly strange as you could just do grep 'second' file.

Upvotes: 1

Related Questions