简体   繁体   中英

How to iterate through an array and output certain words in a bash script?

I am writing a basic bash script to iterate through an array and I have to output the words starting with the letters 't' and 'm'. I used grep to obtain the words starting with certain letters, but I am unable to output more than one letter. How do I use grep to search for more than one starting letter? Or is there a better way to approach this?

 #!/bin/bash
Unix=( "car" "hello" "tony" "mustard" );
echo ${Unix[@]}

echo "Here are the words starting with t + m: "
for i in ${Unix[@]}
do
    echo $i | grep '^\t'
done

I suggest:

grep -e '^t' -e'^m'

or

grep -E '^(m|t)'

See: man grep

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM