Extract part of filename

China☆狼群 提交于 2019-12-11 19:58:13

问题


I have multiple filenames that look something like;

com.test.app1.deb

com.heavy.test.app2.deb

com.maybe-test.app3.deb

com.crazy.app-4.deb

I would like to get the bolded strings only. so far, I've got this,

name=$(echo $file | sed 's!\(*.\)\(.*\).deb!\2!')

EDIT: I have other files in the same dir that would name something like;

com.company.name_1.0.2_arm.deb

Currently, my code looks like;

for file in *.deb; do
 name=$(echo "$file" | sed 's/^.*\.\([^.][^.]*\)\.deb$/\1/')
 echo $name
done

回答1:


You want negative matching so you can exclude dots from the part of the string that you want to capture. I also anchored the string so that you don't get a nasty surprise on a name like com.deboop.foo.deb.

name=$(echo "$file" | sed 's/^.*\.\([^.][^.]*\)\(_[-.0-9][-.0-9]*_arm\)*\.deb$/\1/')

(edited to reflect comments)




回答2:


$> cat text
com.test.app1.deb
com.heavy.test.app2.deb
com.maybe-test.app3.deb
com.crazy.app-4.deb

$> sed -r "s/.*\.([^\.]*)\.deb$/\1/" ./text
app1
app2
app3
app-4



回答3:


pearl.238> cat file1
com.test.app1.deb
com.heavy.test.app2.deb
com.maybe-test.app3.deb
com.crazy.app-4.deb
pearl.239> awk -F. '{print $(NF-1)}' file1
app1
app2
app3
app-4
pearl.240> 

you should use the below in your script.

name=$(echo $file |awk -F. '{print $(NF-1)}')


来源:https://stackoverflow.com/questions/10275818/extract-part-of-filename

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