im using a case statement to search for a pattern in a variable, like this:
case "${VARIABLE}" in
* unix is great *)
echo Found it!
;;
esac
However, what happens if I want to make sure some other string DOES NOT exist on the same line that "unix is great" is on??
with egrep, i can solve it with something like:
echo "${VARIABLE}" | egrep -v "bad lines i dont want" | egrep "unix is great"
I'm hoping there's a way to do this in case, without having to use any external tools.
Try:
case $VARIABLE in
*"bad lines i dont want"*)
:
;;
*"unix is great"*)
echo "Found: $VARIABLE"
;;
esac
1 Like
I tried this but it didn't seem to work. when i run it, i get nothing back. just the prompt.
#!/bin/sh
VARIABLE='bad lines i dont want
unix is great'
case ${VARIABLE} in
*"bad lines i dont want"*)
:
;;
*"unix is great"*)
echo "Found: $VARIABLE"
;;
esac
And I tried putting the variable in quotes:
#!/bin/sh
VARIABLE='bad lines i dont want
unix is great'
case "${VARIABLE}" in
*"bad lines i dont want"*)
:
;;
*"unix is great"*)
echo "Found: $VARIABLE"
;;
esac
neither worked
Of course not. There is only one variable and the expansion of that variable contains the string bad lines i don't want
which is matched by the 1st pattern in your case statement (which produces no output).
If you're dealing with a variable containing multiple lines and you want to process each line separately, you need something more like:
#!/bin/sh
VARIABLE='this line should not print -- bad lines i dont want
this line should print -- unix is great
neither of the above'
printf "%s\n" "$VARIABLE" | while IFS= read -r line
do case "$line" in
*"bad lines i dont want"*) echo "1st case: $line";;
*"unix is great"*) echo "2nd case: Found: $line";;
*) echo "default case: No match: $line";;
esac
done
which produces the output:
1st case: this line should not print -- bad lines i dont want
2nd case: Found: this line should print -- unix is great
default case: No match: neither of the above
2 Likes
The behaviour of the case statement matches what your need actually.
see:
$ cat case.sh
for VARIABLE in 'bad lines i dont want unix is great' 'bad line ... unix is great'
do
((LOOP+=1))
case ${VARIABLE} in
*"bad lines i dont want"*)
echo "Loop : $LOOP :CASE 1: $VARIABLE"
;;
*"unix is great"*)
echo "Loop : $LOOP :CASE 2: $VARIABLE"
;;
esac
done
$ ./case.sh
Loop : 1 :CASE 1: bad lines i dont want unix is great
Loop : 2 :CASE 2: bad line ... unix is great