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
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.
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.
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.
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.
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/'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With