Extract part of filename

2019-09-18 23:22发布

问题:

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)}')