如何获取没有最后 N 个字符的字符串?

Ron*_*adi 1 bash awk

如果我的变量中有一个 bash 字符串。如何提取/检索除最后一个字符之外的字符串,如果我想提取直到最后两个字符,会有多容易?

例子:

# Removing the last character
INPUT="This is my string."
# Expected output "This is my string"

# Removing the last two characters
INPUT="This is my stringoi"
# Expected output "This is my string"
Run Code Online (Sandbox Code Playgroud)

ogu*_*ail 8

对于任何 POSIX shell:

OUTPUT="${INPUT%?}"  # remove last character
OUTPUT="${INPUT%??}" # remove last two characters
                     # and so on
Run Code Online (Sandbox Code Playgroud)


小智 5

样本:

INPUT="This is my string."
echo $INPUT |sed 's/.$//' # removes last character

INPUT="This is my stringoi"
echo $INPUT |sed 's/..$//' # removes last two character
Run Code Online (Sandbox Code Playgroud)

  • 也许您还应该展示一个带有“s/.\{3\}$//”等间隔的示例 (2认同)