#! /bin/bash
# assignment
str="abc"
echo $str
# append
str="efg $str"
# subsutitution
str=$(echo $str | sed -e 's/.* /([a-zA-Z]/+/)$//1/')
echo $str
# strip
str="abc efg"
str=${str##* }
echo $str
# uppercase 2
str="abc"
str=$(echo $str | tr '[a-z]' '[A-Z]')
echo $(echo abc | sed 'y/[a-z]/[A-Z]/')
echo $str
# start with
str="abcdefg"
if [[ $str =~ ^abc ]]; then
echo start with abc
fi
# end with
if [[ $str =~ efg$ ]]; then
echo end with efg
fi
# length
echo "length of $str is ${#str}"
# substring
# ${x:start:length}
echo "$str[0:3] is ${str:0:3}"
echo "$str[3:4] is ${str:3:4}"
# join
OLD_IFS=$IFS
IFS=:
set -- a b c d e
x="$*"
echo "$x"
IFS=$OLD_IFS
# $1=sep $2..list of fields
string_join()
{
if [ $# -ge 2 ]; then
sep=$1
shift
res=$1
shift
while [ $# -ne 0 ]; do
res="$res$sep$1"
shift
done
echo $res
return 0
fi
return 1
}
string_join : 1 2 3 4 5
string_join ";" a "abc" efg
# index
# find abc in 123ababc, res is 5
pattern=abc
string=123ababc
# find $0 in $1
# returns -1 if not found otherwise return the index where $0 in $1
string_index()
{
case $1 in
"") index=0;;
$2)
x=${1%%"$2*"}
index=$((${#x}-1))
;;
*) index=-1
esac
echo $index
if [[ $index != -1 ]]; then
return 0
else
return 1
fi
}
if string_index a b > /dev/null; then
echo a in b
else
echo not found
fi
# swap case
x=aBcD
echo $x | tr '[a-zA-Z]' '[A-Za-z]'
# assignment
str="abc"
echo $str
# append
str="efg $str"
# subsutitution
str=$(echo $str | sed -e 's/.* /([a-zA-Z]/+/)$//1/')
echo $str
# strip
str="abc efg"
str=${str##* }
echo $str
# uppercase 2
str="abc"
str=$(echo $str | tr '[a-z]' '[A-Z]')
echo $(echo abc | sed 'y/[a-z]/[A-Z]/')
echo $str
# start with
str="abcdefg"
if [[ $str =~ ^abc ]]; then
echo start with abc
fi
# end with
if [[ $str =~ efg$ ]]; then
echo end with efg
fi
# length
echo "length of $str is ${#str}"
# substring
# ${x:start:length}
echo "$str[0:3] is ${str:0:3}"
echo "$str[3:4] is ${str:3:4}"
# join
OLD_IFS=$IFS
IFS=:
set -- a b c d e
x="$*"
echo "$x"
IFS=$OLD_IFS
# $1=sep $2..list of fields
string_join()
{
if [ $# -ge 2 ]; then
sep=$1
shift
res=$1
shift
while [ $# -ne 0 ]; do
res="$res$sep$1"
shift
done
echo $res
return 0
fi
return 1
}
string_join : 1 2 3 4 5
string_join ";" a "abc" efg
# index
# find abc in 123ababc, res is 5
pattern=abc
string=123ababc
# find $0 in $1
# returns -1 if not found otherwise return the index where $0 in $1
string_index()
{
case $1 in
"") index=0;;
$2)
x=${1%%"$2*"}
index=$((${#x}-1))
;;
*) index=-1
esac
echo $index
if [[ $index != -1 ]]; then
return 0
else
return 1
fi
}
if string_index a b > /dev/null; then
echo a in b
else
echo not found
fi
# swap case
x=aBcD
echo $x | tr '[a-zA-Z]' '[A-Za-z]'