Linux command to retrieve desired lines

80 views Asked by At

I have data in the following form (stored in file1.txt):

<http://stackoverflow> <isA> "website".
<website> <nameIs> <http://stackoverflow>.

Now using grep I want to retrieve the lines where "http://stackoverflow" occurs as the first string i.e. if I split the lines on spaces then http://stackoverflow should be the first string.

Based on this my output should be:

<http://stackoverflow> <isA> "website".

Is it possible to do so using grep or any other linux command. Because if I use: grep http://stackoverflow file1.txt, then I get the output:

<http://stackoverflow> <isA> "website".
<website> <nameIs> <http://stackoverflow>.

i.e. I get both the lines (whereas my desirable output should contain just the first line of file1.txt):

4

There are 4 answers

0
zedfoxus On BEST ANSWER

Given a few lines like these in a file called t0:

<http://stackoverflow> <isA> "website".
yes <http://stackoverflow> <isA> "website".
<website> <nameIs> <http://stackoverflow>.

This command can do the trick. Notice space after the site:

grep "^<http://stackoverflow> " t0
Result:
<http://stackoverflow> <isA> "website".

If you choose to use awk, you can write something like this:

awk '{ if($1 == "<http://stackoverflow>") {print $0} }' t0

awk is splitting by space and then checking if first item in the split is <http://stackoverflow>. If so, print the entire line represented by $0

0
gturri On

You can use a regular expression:

grep ^http://stackoverflow file1.txt

^ matches the beginning of a line

0
mainframer On
grep ^\<http://stackoverflow file1.txt

^ matches the beginning of a line
\ to match the escape character <

0
Moorthy On

simple use head or tail comamnd

head -1 file1.txt

or

tail -1 file1.txt 

this solution offered based on your post.