如何在unix shell脚本中的最后一个下划线(_)之后获取子字符串

时间:2014-03-19 19:58:09

标签: shell unix substring

我有一个像这样的字符串

this_is_test_string1_22
this_is_also_test_string12_6

我想在最后一个下划线周围分割和提取字符串。 那就是我想要像这样的输出

this_is_test_string1 and 22
this_is_also_test_string12 and 6

任何人都可以帮我解决如何在unix shell脚本中使用它。

感谢。 SREE

3 个答案:

答案 0 :(得分:6)

你可以做到

s='this_is_test_string1_22'

在BASH:

echo "${s##*_}"
22

或使用sed:

sed 's/^.*_\([^_]*\)$/\1/' <<< 'this_is_test_string1_22'
22
sh:

编辑

echo "$s" | sed 's/^.*_\([^_]*\)$/\1/'

答案 1 :(得分:0)

所以从anubhava和glenn中提出想法...... Full Shell脚本可以......如下所示。您可以选择在命令行上输出到文件或显示...

答案 2 :(得分:0)

使用awk

$ awk 'BEGIN{FS=OFS="_"}{last=$NF;NF--;print $0" "last}' <<EOF
> this_is_test_string1_22
> this_is_also_test_string12_6
> EOF
this_is_test_string1 22
this_is_also_test_string12 6