Find a word using AWK

5,300

Solution 1

awk '/(^| )two( |$)/' ...

The (..) groups there are trying to ensure we're only matching "two". At the front it either needs to be the beginning of the line or a space and at the end it needs to be a space or the end of the line. In short, we're making sure the field equals two.

Hmm apparently you can also use word-boundary tags (which looks slightly more elegant but isn't as portable):

awk '/\<two\>' ...

Not sure what your specific use-case is (I assume it's not numbers), you might be just as well off with grep -E '\<two\>' ... but awk will give you a bit more flexibility if you need to do other stuff.

Solution 2

For this simple task you can also use grep:

grep  'two' /path/to/file

output:

one two three four
two three four five

To get the "two" if it is not at the beginning of a line:

grep ' two ' /path/to/file ->one two three four

or with meta-characters to get it only at the beginning of a line:

grep '^two' /path/to/file ->two three four five

Share:
5,300

Related videos on Youtube

Mohammad Reza Rezwani
Author by

Mohammad Reza Rezwani

Msc of computer networks.

Updated on September 18, 2022

Comments

  • Mohammad Reza Rezwani
    Mohammad Reza Rezwani about 1 year

    Is there a way to find a specific record among the whole line?

    This is my file:

    one two three four
    two three four five
    three four five six
    four five six seven
    five six seven eight
    

    How do I search for all lines which include two?

  • Mohammad Reza Rezwani
    Mohammad Reza Rezwani over 9 years
    thanks, for the second part, ( |$) I understand the usage of space. But for $ part , would you please add why $ stand for in here? {I just know $x refers to column x.
  • Oli
    Oli over 9 years
    Simply: the end of the line. ^ means the start.