check a substring in a string in bash

bash, linux

Solution

Use double brackets, which support wildcards:

if [[ $j == *string1* ]]; then

Also, don't parse ls; use a glob instead:

Instead of

for j in `ls `

use

for j in *

If you wan't the match to be case-insensitive, you can set the `shopt -s nocasematch` option:

shopt -s nocasematch
if [[ $j == *string1* ]]; then

Problem

I need a sentence if...else.. that verify if the filename curbing a string specifies in bash ``` for j in `ls ` do if [ "${j:(-3)}" == ".gz" ]; then Cmd="zcat" elif [ "${j:(-4)}" == ".bz2" ]; then Cmd="bzcat" else Cmd="cat" fi if [ $j ***contains*** "string1"]; then $cmd $j | awk -F"," '{print $4}' elif [ $j *contains* "string2" ]; then $cmd $j | awk -F"," '{print $2}' fi done ```

Original source