I have a list of lines of text that I am looping through, looking for a specific term provided as a variable.
Let's say in this case, I am looking for my_search_term = "Ubuntu 2018".
My input lines of text look like this:
- "Ubuntu 20.04LTS"
- "Ubuntu 2018"
... so I am looking for something that will skip over the first string but echo and exit when it matches the second string.
for line in "${list_of_text_lines}"
do
STR=$line
SUB=$my_search_term
if [[ "$STR" =~ .*"$SUB".* ]]; then
echo $line
exit
fi
done
... but instead of echoing "Ubuntu 2018", I get "Ubuntu 20.04LTS". Why?
I appreciate any assistance, and thank you in advance!
Edit 1: As per @Barmar's suggestion, I removed the quotations around my input field, like so:
for line in ${list_of_text_lines}
do
echo ${line}
STR=$line
SUB=$my_search_term
if [[ "$STR" =~ .*"$SUB".* ]]; then
echo $line
exit
fi
done
But this loops through the entire text string without matching, and my echo statements output the following:
...
"Ubuntu
2018"
"Ubuntu
20.04LTS"
...
CodePudding user response:
Without storing command output you can process input and do matching like this:
search_term='Ubuntu 2018'
while IFS= read -r line; do
if [[ $line =~ $search_term ]]; then
echo "matched: $line"
exit
fi
done < <(VBoxManage list vms)
PS: Note that your search term is not a regular expression, it is just a fixed string. In that case you can avoid regex and do glob comparison as well like this:
while IFS= read -r line; do
if [[ $line == $search_term ]]; then
echo "matched: $line"
exit
fi
done < <(VBoxManage list vms)