在bash中,如何修剪字符串的某个部分?

时间:2015-04-12 18:38:32

标签: linux bash unix

我正在尝试仅修改作为参数赋予ltrim()的字符串的左半部分。这是我目前的代码。

ltrim()
{
        string=${1}
        divider=$((${#string} / 2))

        trimrule=${2}

        string_left=${string:0:$divider}
        string_right=${string:$divider}

        echo ${string:$divider} ## My own quick debug lines
        echo ${string:0:$divider} ## My own quick debug lines

        if [ $# -ne 2 ]
        then
                printf "%d argument(s) entered. 2 required.\n" "$#"
        else
                while :
                do
                        case $string_left in
                        ${2}*) string_left=${string_left#?} ;;
                        *${2}) string_left=${string_left%?} ;;
                        *) break ;;
                        esac
                done
                printf "Left side string is %s\n" "${string_left}"
        fi
}

但是,当我输入ltrim abcdefghijklmnopq abc时,shell会返回以下内容:

ijklmnopq 
abcdefgh 
Left side string is bcdefgh

因此,当我希望得到'defgh'时,我只丢失了'a'。我做错了什么?

2 个答案:

答案 0 :(得分:2)

你在寻找这样的东西吗?

function ltrim() {
    echo ${1##$2}
}

ltrim abcdefghijklmnopq abc # Prints: defghijklmnopq

答案 1 :(得分:2)

function substr_remove() {
    echo "${1//$2/}"
}

substr_remove carfoobar123foo456 foo

输出:

carbar123456