Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 如何获取没有最后N个字符的字符串?_Bash_Awk - Fatal编程技术网

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

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

如果变量中有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"
对于任何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\}$/
的示例。是的,同样也可以,谢谢您的通知@奥古斯梅尔