Bash 如何获取没有最后N个字符的字符串?
如果变量中有bash字符串如何提取/检索除最后一个字符以外的字符串,如果要提取到最后两个字符,有多容易 例如:Bash 如何获取没有最后N个字符的字符串?,bash,awk,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 strin
# 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"
对于任何POSIX shell:
OUTPUT="${INPUT%?}" # remove last character
OUTPUT="${INPUT%??}" # remove last two characters
# and so on
样本:
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
编辑:在此处添加通用解决方案。您可以在名为
remove\u char
的awk
中提到要从行尾删除的字符数,然后它应该相应地工作
awk -v remove_char="2" '{print substr($0,1,length($0)-remove_char)}' Input_file
你能试试下面的吗
awk '{print substr($0,1,length($0)-1)}' Input_file
第二种解决方案:使用GNU
awk使字段分隔符无
awk 'BEGIN{FS=OFS=""} {NF--} 1' Input_file
OUTPUT=${INPUT::-1}
?在mac上,我们不能使用与mac无关的负值,它是Bash版本。使用:${OUTPUT:::${#INPUT}-1}
代替。此时,/bin/bash
已经过时,应该被当作macOS兼容POSIX的shell来处理。如果您想使用较新的bash
功能,请安装最新版本或切换到zsh
。也许您还应该显示一个间隔为s/\{3\}$/
的示例。是的,同样也可以,谢谢您的通知@奥古斯梅尔