Get specific string Get specific string shell shell

Get specific string


This should also work if you are looking only for numbers after Tot

[srikanth@myhost ~]$ echo "Abcd1234_Tot9012_tore.dr" | awk ' { match($0,/Tot([0-9]*)/,a); print a[1]; } '9012[srikanth@myhost ~]$ echo "Abcd1234_Tot9012.tore.dr" | awk ' { match($0,/Tot([0-9]*)/,a); print a[1]; } '9012


I know this is tagged as bash/sed but perl is clearer for this kind of task, in my opinion. In case you're interested:

perl -ne 'print $1 if /Tot([0-9]+)[._]/' input.txt

-ne tells perl to loop the specified one-liner over the input file without printing anything by default.

The regex is readable as: match Tot, followed by a number, followed by either a dot or an underscore; capture the number (that's what the parens are for). As it's the first/capture group it's assigned to the $1 variable, which then is printed.


Pure Bash:

string="Abcd1234_Tot9012_tore.dr"        # or ".tore.dr"string=${string##*_Tot}string=${string%%[_.]*}echo "$string"

Remove longest leading part ending with '_Tot'.

Remove longest trailing part beginning with '_' or '.'.

Result:

9012