Extracting a string from a file name

扶醉桌前 提交于 2019-12-08 12:13:37

问题


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

I'm using /bin/sh (which is a requirement)


回答1:


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



回答2:


I think this is what you are looking for.

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

cf

If txt is always upper case and the filename always starts with R you could do something like.

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



回答3:


You can use just the shell (depending what shell your bin/sh is:

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


来源:https://stackoverflow.com/questions/1999682/extracting-a-string-from-a-file-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!