[linux] How to find substring inside a string (or how to grep a variable)?

I'm using BASH, and I don't know how to find a substring. It keeps failing, I've got a string (should this be an array?)

Below, LIST is a string list of database names, SOURCE is the reply, one of those databases. The following still doesn't work:

echo "******************************************************************"
echo "*                  DB2 Offline Backup Script                     *"
echo "******************************************************************"
echo "What's the name of of the  database you would like to backup?"
echo "It will be named one in this list:"
echo ""
LIST=`db2 list database directory | grep "Database alias" | awk '{print $4}'`
echo $LIST
echo ""
echo "******************************************************************"
echo -n ">>> "
read -e SOURCE

if expr match "$LIST" "$SOURCE"; then
    echo "match"
    exit -1
else
    echo "no match"
fi
exit -1

I've also tried this but doesn't work:

if [ `expr match "$LIST" '$SOURCE'` ]; then

This question is related to linux string bash db2

The answer is


Well, what about something like this:

PS3="Select database or <Q> to quit: "
select DB in db1 db2 db3; do
   [ "${REPLY^*}" = 'Q' ] && break
   echo "Should backup $DB..."
done

If you're using bash you can just say

if grep -q "$SOURCE" <<< "$LIST" ; then
    ...
fi

This works in Bash without forking external commands:

function has_substring() {
   [[ "$1" != "${2/$1/}" ]]
}

Example usage:

name="hello/world"
if has_substring "$name" "/"
then
   echo "Indeed, $name contains a slash!"
fi

expr is used instead of [ rather than inside it, and variables are only expanded inside double quotes, so try this:

if expr match "$LIST" "$SOURCE"; then

But I'm not really clear what SOURCE is supposed to represent.

It looks like your code will read in a pattern from standard input, and exit if it matches a database alias, otherwise it will echo "ok". Is that what you want?


expr match "$LIST" '$SOURCE'

don't work because of this function search $SOURCE from begin of the string and return the position just after pattern $SOURCE if found else 0. So you must write another code:

expr match "$LIST" '.*'"$SOURCE" or expr "$LIST" : '.*'"$SOURCE"

The expression $SOURCE must be double quoted so as a parser may set substitution. Single quoted not substitute and the code above will search textual string $SOURCE from the beginning of the $LIST. If you need the beginning of the string subtract the length $SOURCE e.g ${#SOURCE}. You may write also

expr "$LIST" : ".*\($SOURCE\)"

This function just extract $SOURCE from $LIST and return it. You'll get empty string else. But they problem with double double quote. I don't know how it resolve without using additional variable. It's light solution. So you may write in C. There is ready function strstr. Don't use expr index, So is very attractive. But index search not substring and only first char.


You can also compare with wildcards:

if [[ "$LIST" == *"$SOURCE"* ]]


You can use "index" if you only want to find a single character, e.g.:

LIST="server1 server2 server3 server4 server5"
SOURCE="3"
if expr index "$LIST" "$SOURCE"; then
    echo "match"
    exit -1
else
    echo "no match"
fi

Output is:

23
match

Examples related to linux

grep's at sign caught as whitespace How to prevent Google Colab from disconnecting? "E: Unable to locate package python-pip" on Ubuntu 18.04 How to upgrade Python version to 3.7? Install Qt on Ubuntu Get first line of a shell command's output Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? Run bash command on jenkins pipeline How to uninstall an older PHP version from centOS7 How to update-alternatives to Python 3 without breaking apt?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to bash

Comparing a variable with a string python not working when redirecting from bash script Zipping a file in bash fails How do I prevent Conda from activating the base environment by default? Get first line of a shell command's output Fixing a systemd service 203/EXEC failure (no such file or directory) /bin/sh: apt-get: not found VSCode Change Default Terminal Run bash command on jenkins pipeline How to check if the docker engine and a docker container are running? How to switch Python versions in Terminal?

Examples related to db2

DB2 SQL error sqlcode=-104 sqlstate=42601 DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703 How to update multiple columns in single update statement in DB2 Difference between CLOB and BLOB from DB2 and Oracle Perspective? How to AUTO_INCREMENT in db2? DB2 Timestamp select statement insert multiple rows into DB2 database Create a copy of a table within the same database DB2 determine DB2 text string length DB2 Date format