Bash string manipulation

#! /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]'


 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值