LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bash check file for pattern (https://www.linuxquestions.org/questions/programming-9/bash-check-file-for-pattern-862337/)

MTK358 02-12-2011 07:41 PM

Bash check file for pattern
 
How do I write an if statement in Bash so that it executes only if the first line in a file matches or doesn't match a regex?

crts 02-12-2011 07:53 PM

Do you mean something like this
Code:

if [[ "$(head -n1 file)" =~ RegEx ]];then
...
else
...
fi

Notice, that the RegEx is not enclosed in braces, quotes or whatsoever.
Alternatively,
Code:

read var < file
if [[ "$var" =~ RegEx ]];then
...
else
...
fi


MTK358 02-12-2011 08:00 PM

Is it OK if the regex contains whitespace, are quotes still not needed?

crts 02-12-2011 08:11 PM

Quote:

Originally Posted by MTK358 (Post 4256599)
Is it OK if the regex contains whitespace, are quotes still not needed?

Nope, but you have to escape the spaces. Bash does "funny" things with your RegEx if you enclose it in quotes. Go ahead and see for yourself what happens:
Code:

set -x
if [[ $(read ...) =~ "some space .*" ]]; ...

Notice, how '.*' gets mangled. Maybe there is a shopt or setting to control this behavior. Not sure.

Nominal Animal 02-13-2011 12:57 AM

If you use sh or older bash versions without [[ support, you can always use sed:
Code:

if sed -ne '1 { /pattern/ q0 } ; q1' file ; then
    echo file contains pattern on the first line
fi

When invoked like this, sed only reads the first line of file.

Hope this helps,
Nominal Animal


All times are GMT -5. The time now is 06:03 PM.