Extracting a string from a filename

My script accepts a filename in the form R # TYPE.TXT (# is a number, and TYPE is two or three characters). I want my script to give me a TYPE. What should I do to get it? I think I need to use awk and sed.

I am using / bin / sh (which is a must)

0


source to share


3 answers


you can use awk

$ echo R1CcC.TXT | awk '{sub(/.*[0-9]/,"");sub(".TXT","")}{print}'
CcC

      

or



$ echo R1CcC.TXT | awk '{gsub(/.*[0-9]|\.TXT$/,"");print}'
CcC

      

and if sed is really what you want

$ echo R9XXX.TXT | sed 's/R[0-9]\(.*\)\.TXT/\1/'
XXX

      

+1


source


I think this is what you are looking for.

$ echo R3cf.txt | sed "s/.[0-9]\(.*\)\..*/\1/"

cf

      



If txt is always uppercase and the filename always starts with R, you can do something like.

$ echo R3cf.txt | sed "s/R[0-9]\(.*\)\.TXT/\1/"

      

+1


source


You can only use the shell (depending on the shell it is in bin/sh

:

f=R9ABC.TXT
f="${f%.TXT}"       # remove the extension
type="${f#R[0-9]}"  # remove the first bit
echo "$type"        # ==> ABC

      

0


source







All Articles