3

I have a file in which value starts with ABC or ABD.

After fetching the value from input file how to check it starts with ABC or ABD?

eg:

value=$(cat file | awk 'NF{print;exit}' | awk '{print $1}')

and now I want to check this $value is starting with ABC or ABD . how?

thomasrutter
  • 36,774
Anony
  • 773
  • How are you fetching it? In a character array? – Jay Jan 12 '18 at 03:43
  • No. value=$(cat file | awk 'NF{print;exit}' | awk '{print $1}') and now I want to check this $value is starting with ABC or ABD – Anony Jan 12 '18 at 03:44
  • Please update your question accordingly with these details. – Jay Jan 12 '18 at 03:46
  • 2
    Why check it in bash? why not check it in awk, since you're already using that? – steeldriver Jan 12 '18 at 03:52
  • There are several ways to do anything. grep is often used for pattern matching. see man grep Related:https://askubuntu.com/questions/587264/how-to-find-lines-matching-a-pattern-and-delete-them – Elder Geek Jan 12 '18 at 04:13
  • FYI there's no need to use cat, and there's no need to use awk twice: your command can be reduced to awk 'NF {print $1; exit}' file – steeldriver Jan 12 '18 at 04:20
  • I have to fetch value from a file that s why cat. Yea, awk oen is true..Thank you.. – Anony Jan 12 '18 at 04:32

2 Answers2

7

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
John1024
  • 13,687
  • 43
  • 51
2

Try this:

 echo $value | grep -c "^AB[CD]"

This will return 1 if the pattern is present at the beginning.

Jay
  • 2,270