Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a substring after the last underscore (_) in unix shell script

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

like image 809
Sree Avatar asked Mar 19 '14 19:03

Sree


People also ask

What is Subsub-string in Bash?

Sub-string is nothing but extracting a part of a string. In an earlier article, we discussed the various ways of how to extract a sub-string from every line in a file. In this article, we will see how to extract sub-string exclusively in bash / ksh93 and its options.

What is the substring length command?

Moreover, this substring extraction is an internal command, and hence it is very good from performance perspective: length specifies the length of characters to be extracted from the offset.

How to extract the first 3 characters of a substring?

Moreover, this substring extraction is an internal command, and hence it is very good from performance perspective: length specifies the length of characters to be extracted from the offset. 1. To extract the first 3 characters : In the offset, 0 indicates the 1st character, 1 indicates 2nd character and so on.

How to get the substring of a string in Python?

In our first example, we will define a string named “string” with some value in it having some characters and numbers. We will use the keyword “cut” in this code, followed by “-d,” to obtain the substring of the particular string.


2 Answers

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/'
like image 168
anubhava Avatar answered Oct 24 '22 10:10

anubhava


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
like image 38
jaypal singh Avatar answered Oct 24 '22 10:10

jaypal singh