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

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

提交回复
热议问题