How to get a 1st line which matches the particular pattern?

Hi all,

I have file on which I do grep on "/tmp/data" then I get 5 lines as

dir Path: /tmp/data/20162343134
Starting to listen on ports logging: 
--
Moving results files from local storage: /tmp/resultsFiles/20162343134/*.gz to NFS: /data/temp/20162343134/outgoing

from above got to get 1st line dir Path: /tmp/data/20162343134

thanks
--girija

Why should you get above 5 lines from a grep "/tmp/data" ? Please show your command and a small but representative sample.

It would be interesting to see what grep command produced those four lines of output. And, if you think there are five lines there, it would be nice if you also showed us the other line.

But, depending on the options and operands you fed to grep to get that output, it would seem that unless other lines in /tmp/data contain the string Path: , you could get what you want just by using:

grep -F "Path:" /tmp/data

Being in the mind-reading business for so long i used the "applied conjecture"-method (also called "wild guessing procedure") and found out what you more or less probably want perhaps to be eventually done:

You have a file and filter some lines with a grep -statement. The filter matches several lines and you want only the first oneof these matches. (If this is not the case: don't bother telling us - we are all psychics.)

If so: you can either pipe that through the head -utility:

grep "<some-regex>" /path/to/file | head

or, more elegantly, use sed to do all in one:

sed -n '/<some-regex>/ {;p;q;}' /path/to/file

I hope this helps.

bakunin

Could use awk too:

awk '/"dir Path"/ ;NR==1 {print $3}' forum.data 

Where forum.data is the input file, containing the 4 lines from post1.

Hope this helps

There aren't any double quotes in the input, and if the data we have been shown is the result of an earlier grep command, there is no reason to believe that the 1st line in the grep output was the 1st line in the original file. And, the request was for the entire line; not just the last field. So, if you want to do this with awk , shouldn't it just be:

awk '/dir Path:/' forum.data

I did add the double quotes as i was getting a 2 line output without them (while writing)... :confused:

Ah, yes. With the data shown in the post #1 in this thread:

  • /dir Path/; would print the 1st line once, and
  • NR==1 {print $3} would print the 3rd field in that line again.

Changing /dir Path/ to /"dir Path"/ eliminated the 1st output line because it no longer matches any input.

1 Like