0

I need to check whether a file contains an exact string, say string12345, but not string123456 for example. This string can contain spaces! The file consists of various rows that all need to be checked.

But the string can be in a different place on the row, between dividing characters. The dividing characters can be either | or ,. Finally, the string can also be at the start or end of the row.

The check per row I have working so far is:

sLineFromFile=$(cat "${fFileToCheck}" | grep ^${sStringToCheck},)

So if sLineFromFile is not empty, I know the file (fFileToCheck) contains sStringToCheck, but only at the start of the line ^ and when followed by a comma ,.

I'm looking then for some kind of OR feature like this:

sLineFromFile=$(cat "${fFileToCheck}" | grep [^,|]${sStringToCheck}[,|$])

I thought that this would work based on this Unix & Linux SE link but instead it appears to take the characters literally as written (so sLineFromFile is always empty). I have tried many variations including:

sLineFromFile=$(cat "${fFileToCheck}" | grep @[^,|]${sStringToCheck},)
sLineFromFile=$(cat "${fFileToCheck}" | grep (^,|)${sStringToCheck},)
sLineFromFile=$(cat "${fFileToCheck}" | grep '[^,|]${sStringToCheck},')
sLineFromFile=$(cat "${fFileToCheck}" | grep [^,|]${sStringToCheck},)

(here just testing the character before sStringToCheck).

How should I correct this?

Community
  • 1
  • 1
  • Many [cats](http://stackoverflow.com/questions/11710552/useless-use-of-cat) were harmed in the production of this question... `grep ` is a good thing... – twalberg Aug 28 '13 at 14:55

1 Answers1

1

I see two options :

  1. If stringToCheck contains only the word characters(alphanumeric+underscore), you can use:

     grep -w "$stringToCheck" file
    
  2. Otherwise, use the following :

     grep -E "(^|[\|,])$stringToCheck([\|,]|$)" file
    

I think this should solve your problem.

Again instead of getting the whole matched line, you can achieve the same using something like :

c=$(grep -Ec "(^|[\|,])$stringToCheck([\|,]|$)" file)
if [ $c -eq 0 ]
then
echo noMatch
else
echo hasMatch
fi
blackSmith
  • 3,054
  • 1
  • 20
  • 37
  • Thanks. Problem with the first one is that `sStringToCheck` can contain *spaces*! I will update the question. I cannot get your second solution working - the string is not found. – Reinstate Monica - Goodbye SE Aug 28 '13 at 13:01
  • I've updated the answer. Forgot to add the -E option. Have a try now. If possible add some sample. Interestingly, -w option works with spaces also, just tested that. – blackSmith Aug 28 '13 at 13:10
  • That's weird. May be the test data set I'm using is not appropriate. Please add a sample file along with the string you searched for, and your problem will be solved ASAP. – blackSmith Aug 28 '13 at 13:45
  • Apparently we have multiple `grep` versions. When I used the correct one it (the `hasMatch` second solution) worked perfectly. Thanks! – Reinstate Monica - Goodbye SE Aug 29 '13 at 13:10