如果我的变量中有一个 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)
对于任何 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)