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?

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.

  • 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. – Mohammad Reza Rezwani Jul 9 '14 at 20:05
  • 1
    Simply: the end of the line. ^ means the start. – Oli Jul 9 '14 at 20:12

For this simple task you can also use grep:

grep  'two' /path/to/file


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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.