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

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

    You could use sed,

    sed 's/.\{4\}$//' <<< "$var"
    

    EXample:

    $ var="some string.rtf"
    $ var1=$(sed 's/.\{4\}$//' <<< "$var")
    $ echo $var1
    some string
    
    0 讨论(0)
  • 2020-11-28 19:44

    First, it's usually better to be explicit about your intent. So if you know the string ends in .rtf, and you want to remove that .rtf, you can just use var2=${var%.rtf}. One potentially-useful aspect of this approach is that if the string doesn't end in .rtf, it is not changed at all; var2 will contain an unmodified copy of var.

    If you want to remove a filename suffix but don't know or care exactly what it is, you can use var2=${var%.*} to remove everything starting with the last .. Or, if you only want to keep everything up to but not including the first ., you can use var2=${var%%.*}. Those options have the same result if there's only one ., but if there might be more than one, you get to pick which end of the string to work from. On the other hand, if there's no . in the string at all, var2 will again be an unchanged copy of var.

    If you really want to always remove a specific number of characters, here are some options.

    You tagged this bash specifically, so we'll start with bash builtins. The one which has worked the longest is the same suffix-removal syntax I used above: to remove four characters, use var2=${var%????}. Or to remove four characters only if the first one is a dot, use var2=${var%.???}, which is like var2=${var%.*} but only removes the suffix if the part after the dot is exactly three characters. As you can see, to count characters this way, you need one question mark per unknown character removed, so this approach gets unwieldy for larger substring lengths.

    An option in newer shell versions is substring extraction: var2=${var:0:${#var}-4}. Here you can put any number in place of the 4 to remove a different number of characters. The ${#var} is replaced by the length of the string, so this is actually asking to extract and keep all the characters from indexes 0 to (length - 4), inclusive. With this approach, you lose the option to make the change only if the string matches a pattern; no matter what the actual value of the string is, the copy will include all but its last four characters.

    Bash lets you leave the start index out; it defaults to 0, so you can shorten that to just var2=${var::${#var}-4}. In fact, newer versions of bash (specifically 4+, which means the one that ships with MacOS won't work) recognize negative indexes as counting back from the end of the string, so you can get rid of the length expression, too: var2=${var::-4}.

    If you're not actually using bash but some other POSIX-type shell, the pattern-based suffix removal with % will still work – even in plain old dash, where the index-based substring extraction won't. Ksh and zsh do both support substring extraction, but require the explicit 0 start index; zsh also supports the negative end index, while ksh requires the length expression.

    Instead of using built-in shell parameter expansion, you can of course run some utility program to modify the string and capture its output with command substitution. There are plenty that will work, but something like var2=$(cut -c -4 <<<"$var") is probably the shortest option.

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

    This worked for me by calculating size of string.
    It is easy you need to echo the value you need to return and then store it like below

    removechars(){
            var="some string.rtf"
            size=${#var}
            echo ${var:0:size-4}  
        }
        removechars
        var2=$?
    

    some string

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

    What worked for me was:

    echo "hello world" | rev | cut -c5- | rev
    # hello w
    

    But I used it to trim lines in a file so that's why it looks awkward. The real use was:

    cat somefile | rev | cut -c5- | rev
    

    cut only gets you as far as trimming from some starting position, which is bad if you need variable length rows. So this solution reverses (rev) the string and now we relate to its ending position, then uses cut as mentioned, and reverses (again, rev) it back to its original order.

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

    I tried the following and it worked for me:

    #! /bin/bash
    
    var="hello.c"
    length=${#var}
    endindex=$(expr $length - 4)
    echo ${var:0:$endindex}
    

    Output: hel

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

    In this case you could use basename assuming you have the same suffix on the files you want to remove.

    Example:

    basename -s .rtf "some string.rtf"
    

    This will return "some string"

    If you don't know the suffix, and want it to remove everything after and including the last dot:

    f=file.whateverthisis
    basename "${f%.*}"
    

    outputs "file"

    % means chop, . is what you are chopping, * is wildcard

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