10

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

Sree
  • 921
  • 2
  • 12
  • 31

3 Answers3

13

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/'
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    And to achieve the desired output: `new="${s%_*} and ${s##*_}"; echo "$new"` – glenn jackman Mar 19 '14 at 20:08
  • 1
    I am using /bin/sh interpreter and I am getting error when using echo sed 's/^.*_\([^_]*\)$/\1/' <<< 'this_is_test_string1_22'. The error is "syntax error: `<' unexpected" – Sree Mar 19 '14 at 20:57
  • 2
    An explanation of the first method would be nice, i.e. what does ##* mean? Here is one: https://stackoverflow.com/questions/2059794/what-is-the-meaning-of-the-0-syntax-with-variable-braces-and-hash-chara – compguy24 Feb 27 '19 at 13:25
1

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
jaypal singh
  • 74,723
  • 23
  • 102
  • 147
0

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
Ronak Patel
  • 3,819
  • 1
  • 16
  • 29