Bash string manipulation

來源:互聯網
上載者:User
#! /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]'

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.