Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 5 down vote accepted
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.

share|improve this answer
    
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. –  lion Jul 9 at 20:05
1  
Simply: the end of the line. ^ means the start. –  Oli Jul 9 at 20:12

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|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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