Using case
To check if a shell variable starts with ABC or ABD, a traditional (and very portable) method is to use a case statement:
case "$value" in
AB[CD]*) echo yes;;
*) echo no;;
esac
Because this requires no external processes, it should be fast.
Using [
Alternatively, one can use a test command:
if [ "${value#AB[CD]}" != "$value" ]
then
echo yes
else
echo no
fi
This is also quite portable.
Using [[
Lastly, one can use the more modern and less portable test command:
if [[ $value == AB[CD]* ]]
then
echo yes
else
echo no
fi
Reading the file and testing all in one step
To read the first nonempty line of a file and test if its first field start with ABC or ABD:
awk 'NF{if ($1~/^AB[CD]/) print "yes"; else print "no";exit}' file
bash
? why not check it inawk
, since you're already using that? – steeldriver Jan 12 '18 at 03:52grep
is often used for pattern matching. seeman grep
Related:https://askubuntu.com/questions/587264/how-to-find-lines-matching-a-pattern-and-delete-them – Elder Geek Jan 12 '18 at 04:13cat
, and there's no need to useawk
twice: your command can be reduced toawk 'NF {print $1; exit}' file
– steeldriver Jan 12 '18 at 04:20