如何在bash字符串choping中切断字符串的最后n个字节?

jai*_*hen 14 bash

例如qa_sharutils-2009-04-22-15-20-39,想要砍掉最后20个字节,然后得到' qa_sharutils'.

我知道如何在sed中做到这一点,但为什么$A=${A/.\{20\}$/}不起作用?

谢谢!

Cha*_* Ma 37

如果你的字符串存储在一个名为$ str的变量中,那么这将为你提供bash中没有最后20位的子字符串

${str:0:${#str} - 20}
Run Code Online (Sandbox Code Playgroud)

基本上,字符串切片可以使用

${[variableName]:[startIndex]:[length]}
Run Code Online (Sandbox Code Playgroud)

并且字符串的长度是

${#[variableName]}
Run Code Online (Sandbox Code Playgroud)

编辑:使用sed解决方案的解决方案:

sed 's/.\{20\}$//' < inputFile
Run Code Online (Sandbox Code Playgroud)

  • `$ {str :: - 20}}`就够了. (4认同)