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

后端 未结 10 2435
后悔当初
后悔当初 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:56

    Hope the below example will help,

    echo ${name:0:$((${#name}-10))} --> ${name:start:len}

    • In above command, name is the variable.
    • start is the string starting point
    • len is the length of string that has to be removed.

    Example:

        read -p "Enter:" name
        echo ${name:0:$((${#name}-10))}
    

    Output:

        Enter:Siddharth Murugan
        Siddhar
    

    Note: Bash 4.2 added support for negative substring

    0 讨论(0)
  • 2020-11-28 19:57

    You can do like this:

    #!/bin/bash
    
    v="some string.rtf"
    
    v2=${v::-4}
    
    echo "$v --> $v2"
    
    0 讨论(0)
  • 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}

    0 讨论(0)
  • 2020-11-28 20:05

    To remove four characters from the end of the string use ${var%????}.

    To remove everything after the final . use ${var%.*}.

    0 讨论(0)
提交回复
热议问题