How to remove last n characters from a string in Bash?

后端 未结 10 2518
后悔当初
后悔当初 2020-11-28 19:20

I have a variable var in a Bash script holding a string, like:

echo $var
\"some string.rtf\"

I want to remove the last 4 chara

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 19:59

    Using Variable expansion/Substring replacement:

    ${var/%Pattern/Replacement}

    If suffix of var matches Pattern, then substitute Replacement for Pattern.

    So you can do:

    ~$ echo ${var/%????/}
    some string
    

    Alternatively,

    If you have always the same 4 letters

    ~$ echo ${var/.rtf/}
    some string
    

    If it's always ending in .xyz:

    ~$ echo ${var%.*}
    some string
    

    You can also use the length of the string:

    ~$ len=${#var}
    ~$ echo ${var::len-4}
    some string
    

    or simply echo ${var::-4}

提交回复
热议问题