0

如果我在变量中有一个 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"
4

3 回答 3

4

使用任何 POSIX shell:

OUTPUT="${INPUT%?}"  # remove last character
OUTPUT="${INPUT%??}" # remove last two characters
                     # and so on
于 2019-10-22T14:33:12.000 回答
3

样本:

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
于 2019-10-22T14:34:11.997 回答
2

编辑:在此处添加通用解决方案。awk您可以在命名中提及要从行尾删除的字符数,remove_char然后它应该相应地工作。

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
于 2019-10-22T14:39:09.787 回答