Match a string from file and print only the first row that matching

Viewed 107

I am trying to match a string from file and only print the first line that matches the string. I am able to get the result using grep but is there a way I can achieve the same output using awk?

# cat file
/dev/sdac
/dev/cciss/c0d0
/dev/cciss/c0d0p1
/dev/cciss/c0d0p2
/dev/cciss/c0d0p1

# grep -wm1 c0d0p1 file
/dev/cciss/c0d0p1
1 Answers

Could you please try following.

awk '/c0p0d1/{print;exit}' Input_file

Explanation: I am searching string in each line and when a match is found I am printing the line and exiting ASAP since we need not to read file unnecessary. Exiting from program will make it faster too.

Related