Showing posts with label substring. Show all posts
Showing posts with label substring. Show all posts

Wednesday, January 14, 2015

Bash - Find substring in a string

Very simple solution to find substring in a string, make script sub.sh:
#!/bin/bash
txt="This is a text"
substr="text"
if [[ $txt == *$substr* ]]
then
echo "String [$txt] contains substring [$substr]"
else
echo "String [$txt] doesn't contains substring [$substr]"
fi

Variable txt is a string which should (or not) contains string from variable substr.

Output:
$ ./sub.sh
String [This is a text] contains substring [text]

Change variable substr:
substr="t1xt"

Output:
$ ./sub.sh
String [This is a text] doesn't contains substring [t1xt]

Monday, May 12, 2014

Bash - Substring

How to get substring in Bash script? Simple :)

if we have string:

$ a=123456789

substring from position 1 to 5 is

$ echo ${a:1:5}
23456

First position in a string is 0.

in general: ${varname:start_pos:length}