grep -w with only space as delimiter
Asked Answered
F

4

6
grep -w uses punctuations and whitespaces as delimiters. 

How can I set grep to only use whitespaces as a delimiter for a word?

Fatherinlaw answered 7/6, 2012 at 12:1 Comment(2)
Please improve your question by posting the relevant sections of code you've tried, properly formatted. In addition, please post whatever samples you're using as a corpus to test against.Blade
the question is very simple and does require a code to be pasted. It's a theoretical question. William Pursell understood it and answered it correctly.Fatherinlaw
C
3

If you want to match just spaces: grep -w foo is the same as grep " foo ". If you also want to match line endings or tabs you can start doing things like: grep '\(^\| \)foo\($\| \)', but you're probably better off with perl -ne 'print if /\sfoo\s/'

Caudate answered 7/6, 2012 at 12:27 Comment(0)
C
2

You cannot change the way grep -w works. However, you can replace punctuations with, say, X character using tr or sed and then use grep -w, that will do the trick.

Concessionaire answered 7/6, 2012 at 12:10 Comment(0)
B
2

The --word-regexp flag is useful, but limited. The grep man page says:

   -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.

If you want to use custom field separators, awk may be a better fit for you. Or you could just write an extended regular expression with egrep or grep --extended-regexp that gives you more control over your search pattern.

Blade answered 7/6, 2012 at 12:16 Comment(2)
how can i do it with awk? i want to search for a particular word in a line. if it is there i have to consider the line else ignore itFatherinlaw
@ganducoder Please update your question with the relevant section of the code that you're currently working on; folks will be glad to help, but won't write it for you. In addition, include whatever samples you're using as a corpus to test against.Blade
A
0

Use tr to replace spaces with new lines. Then grep your string. The contiguous string I needed was being split up with grep -w because it has colons in it. Furthermore, I only knew the first part, and the second part was the unknown data I needed to pull. Therefore, the following helped me.

echo "$your_content" | tr ' ' '\n' | grep 'string'
Apologue answered 12/11, 2019 at 23:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.