XYZ_Linux
XYZ_Linux

Reputation: 3607

extract a line from a file using csh

I am writing a csh script that will extract a line from a file xyz. the xyz file contains a no. of lines of code and the line in which I am interested appears after 2-3 lines of the file. I tried the following code

set product1 = `grep -e '<product_version_info.*/>' xyz`

I want it to be in a way so that as the script find out that line it should save that line in some variable as a string & terminate reading the file immediately ie. it should not read furthermore aftr extracting the line.

Please help !!

Upvotes: 1

Views: 3398

Answers (2)

gpojd
gpojd

Reputation: 23075

grep has an -m or --max-count flag that tells it to stop after a specified number of matches. Hopefully your version of grep supports it.

set product1 = `grep -m 1 -e '<product_version_info.*/>' xyz`

From the man page linked above:

-m NUM, --max-count=NUM

    Stop reading a file after NUM matching lines.  If the  input  is
    standard  input  from a regular file, and NUM matching lines are
    output, grep ensures that the standard input  is  positioned  to
    just  after the last matching line before exiting, regardless of
    the presence of trailing context lines.  This enables a  calling
    process  to resume a search.  When grep stops after NUM matching
    lines, it outputs any trailing context lines.  When  the  -c  or
    --count  option  is  also  used,  grep  does  not output a count
    greater than NUM.  When the -v or --invert-match option is  also
    used, grep stops after outputting NUM non-matching lines.

As an alternative, you can always the command below to just check the first few lines (since it always occurs in the first 2-3 lines):

set product1 = `head -3 xyz | grep -e '<product_version_info.*/>'`

Upvotes: 2

radical7
radical7

Reputation: 9124

I think you're asking to return the first matching line in the file. If so, one solution is to pipe the grep result to head

set product1 = `grep -e '<product_version_info.*/>' xyz | head -1`

Upvotes: 0

Related Questions