1

I have this sample file for my input:

xyxxyx xyxx xxyx yxyy yxyx
xxyxxx xx xyx xxx x y x xxyy
yxxy xyxxy xxy y x y
xyxy xyx yyxx xyyxyxy xyx
yxyy xyy yxyx xxyxyyx

And I tried to find only "xyx" word if exist in line and return line number. for example in this input just line 2 and 4 have "xyx", and the result I desired is only would be 2 and 4 (line numbers) but grep command give me all 5 lines. this result:

grep -n "xyx" test | cut -f1 -d:
1
2
3
4
5

If I run follow command without cut -f1 -d" I see that find all "xyx" such as in "xyxxyx", "xyxx", "xxyx" and "yxyx" for example in first line, while that is wrong, my pattern only and only exist in line 2 and 4 and it is third word in line 2 and second & 5th word in line 4. See the screen shot:

                          enter image description here

And the result what I want is, only find separated "xyx" and return line number of that.

output of I desired if pattern exist, it is just:

2
4

output of I desired if pattern not exist, it is just:

1
3
5

and also I don't know which command I should use to check if pattern not exist. I tried with all possible combination of grep command but I failed.

Thank you for helping in advance.

0

1 Answer 1

2

You need to add the -w option

$ grep -wn 'xyx' file | cut -d: -f1
2
4

From man grep

   -w, --word-regexp
          Select  only  those  lines  containing  matches  that form whole
          words.  The test is that the matching substring must  either  be
          at  the  beginning  of  the  line,  or  preceded  by  a non-word
          constituent character.  Similarly, it must be either at the  end
          of  the  line  or  followed by a non-word constituent character.
          Word-constituent  characters  are  letters,  digits,   and   the
          underscore.

To invert the match, add the -v switch i.e.

grep -vwn 'xyx' file | cut -d: -f1
1
  • I have added it Sep 4, 2014 at 20:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .