如何从字符串变量中提取最后一个 X 字符?

mem*_*und 6 bash

我正在将文件的最后一行读入变量。然后我想获取字符串变量的最后 X 个字符:

#!/bin/bash
someline="this is the last line content"
echo ${someline}
somepart=${someline: -5}
echo ${somepart}
Run Code Online (Sandbox Code Playgroud)

运行: sh lastchars.sh

结果:

this is the last line content
line 4: Bad substitution
Run Code Online (Sandbox Code Playgroud)

这里可能有什么问题?

ter*_*don 20

听起来你根本没有使用bash。如果我使用dash代替,我只能重现您显示的错误bash

  1. bash

    $ line="someline content"
    $ echo ${line}
    someline content
    $ lastchars=${line: -5}
    $ echo ${lastchars}
    ntent
    
    Run Code Online (Sandbox Code Playgroud)
  2. dash

    $ line="someline content"
    echo ${line}
    lastchars=${line: -5}
    echo ${lastchars}
    $ someline content
    $ dash: 3: Bad substitution
    
    Run Code Online (Sandbox Code Playgroud)

您的shebang 行指向bash,但您正在使用 运行脚本sh,因此忽略 shebang。/bin/sh在 Ubuntu 系统上实际上是dash一个最小的 shell,它不支持您尝试使用的语法。

使用 shebang 行时,没有理由为脚本显式调用 shell,只需使其可执行 ( chmod a+x /path/to/script.sh) 并在不指定解释器的情况下运行它:

/path/to/script.sh
Run Code Online (Sandbox Code Playgroud)

或者,只需使用正确的:

bash /path/to/script.sh
Run Code Online (Sandbox Code Playgroud)

  • @membersound 有关为什么在运行 `sh lastchars.sh` 时忽略 `#!/bin/bash` 行的详细信息,请参阅 [解释器是否读取了 #!/bin/sh?](https://askubuntu. com/questions/238002/is-bin-sh-read-by-the-interpreter)(适用于任何“hashbang”行,包括`#!/bin/bash`,而不仅仅是`#!/bin/ sh`)。 (4认同)