How to get a substring after the last underscore (

2020-02-07 03:39发布

I have a String like this

this_is_test_string1_22
this_is_also_test_string12_6

I wanted to split and extracts string around the last underscore. That is i wanted the outputs like this

this_is_test_string1 and 22
this_is_also_test_string12 and 6

Can anyone help me how to get this in unix shell scripting.

Thanks. Sree

3条回答
2楼-- · 2020-02-07 03:53

You can do

s='this_is_test_string1_22'

In BASH:

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

OR using sed:

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

EDIT for sh:

echo "$s" | sed 's/^.*_\([^_]*\)$/\1/'
查看更多
孤傲高冷的网名
3楼-- · 2020-02-07 03:53

So puting ideas from anubhava and glenn... Full Shell script can be... as follwoing. you can choose to output to a file or display on the commandline...

#!/bin/ksh

#FILE=/paht/to/file.txt or you can pass argument FILE=$1

 FILE=$1
 counter=`wc -l $FILE |cut  -d " " -f1`

x=1

while [ $x -le $counter ]
    do
            REC=`sed -n ${x}p $FILE`

            echo " ${REC%_*} and ${REC##*_} " >> output.txt

    let x=$x+1
done
查看更多
乱世女痞
4楼-- · 2020-02-07 04:10

Using 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
查看更多
登录 后发表回答