Thursday, April 18, 2024
30
rated 0 times [  30] [ 0]  / answers: 1 / hits: 213448  / 2 Years ago, wed, october 5, 2022, 9:14:00

I want to see if a string is inside a portion of another string.

e.g.:



'ab' in 'abc' -> true
'ab' in 'bcd' -> false


How can I do this in a conditional of a bash script?


More From » command-line

 Answers
2

You can use the form ${VAR/subs} where VAR contains the bigger string and
subs is the substring your are trying to find:



my_string=abc
substring=ab
if [ "${my_string/$substring}" = "$my_string" ] ; then
echo "${substring} is not in ${my_string}"
else
echo "${substring} was found in ${my_string}"
fi


This works because ${VAR/subs} is equal to $VAR but with the first occurrence of the string subs removed, in particular if $VAR does not contains the word subs it won't be modified.


[#31059] Thursday, October 6, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ormlai

Total Points: 292
Total Questions: 106
Total Answers: 115

Location: Cape Verde
Member since Fri, Sep 16, 2022
2 Years ago
ormlai questions
Wed, Sep 28, 22, 00:17, 2 Years ago
Sun, Aug 7, 22, 22:05, 2 Years ago
Wed, Jun 16, 21, 03:50, 3 Years ago
Sun, Feb 6, 22, 09:11, 2 Years ago
Mon, Jul 12, 21, 10:00, 3 Years ago
;