0

I would like to find the position of a given word in a text file. For instance if I define word variable as abloom word. I would like to find out I used this command

grep -n "$word" mydict.txt

but if I define the word variable as "ab". Codes gives the every line which has "ab". For example it gives as well word abloom but I only want ab word's line.

1
  • 1
    Please edit your question and add i) an example input file ii) the output you want from that example and iii) tell us what operating system you are using. I suspect you are on Linux so you just want grep -w but I can't know.
    – terdon
    Commented Dec 21, 2021 at 11:32

1 Answer 1

5

You mean, you want to find line #3 here, but not line #1?

abcdefg
foobar
ab cd ef

If so, grep -w might work for you (GNU manpage):

-w, --word-regexp
Select only those lines containing matches that form whole words.

What counts as a "word" depends a bit on the locale. In the C locale, "word characters" are letters, digits and the underscore.

So, in these, ab is a single whole word:

printf 'ab' | grep -w ab
printf 'ab cd' | grep -w ab
printf 'ab-cd' | grep -w ab
printf 'ab, cd' | grep -w ab

But not here:

printf 'ab_cd' | grep -w ab
printf 'ab1' | grep -w ab

You must log in to answer this question.

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