1

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
1

1 Answer 1

1

I suggest:

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

or

grep -E '^(m|t)'

See: man grep

Sign up to request clarification or add additional context in comments.

2 Comments

@MiSully Consider accepting the answer by clicking the green mark next to it if it solves your problem
I suggest to replace echo $i | grep ... with if [[ "$i" =~ ^(m|t) ]]; then echo "$i"; fi. This does not require an external program (grep) and no pipe (two new processes).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.