How to extract name of file?

狂风中的少年 提交于 2019-12-13 05:45:22

问题


In a dir i have some files which looks something like;

org.coy.application_0.1-2_arm.deb

com.cpo.app2_1.2.1_arm.deb

sg.team.works.app3a_1.33_arm.deb

com.share.name4.deb

com.sha-re.app5.deb

com.sha.re.anything.deb

I only require the bolded names.

here's what i have so far;

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

回答1:


for i in *.deb
do
    name=${i%.deb}      #<-- remove extension      (.deb)
    name=${name%%_*}    #<-- remove version        (_x.y.z_arm)
    name=${name##*.}    #<-- remove namespace      (comp.x.y.z)
    echo $name
done

output

app2
anything
app5
name4
application
app3a



回答2:


The best solution would be to use dpkg-query with appropriate options. Check For more information




回答3:


you can use the basename command to make things a bit easier

for file in *.deb; do
 name=`basename $file | sed -e 's/.*\.//' -e 's/_.*//'`
 echo $name
done



回答4:


One way using perl:

perl -e '
    do { 
        printf qq[%s\n], $+{my} 
            if $ARGV[0] =~ m/(?(?=.*_)\.(?<my>[^._]+)_\d|.*\.(?<my>[^.]+)\.deb\Z)/ 
    } while shift && @ARGV
' *.deb

Explanation of the regexp:

(?                          # Conditional expression.
(?=.*_)                     # Positive look-ahead to check if exits '_' in the string.
\.(?<my>[^._]+)_\d          # If previous look-ahead succeed, match string from a '.' until
                            # first '_' followed by a number.
|                           # Second alternative when look-ahead failed.
.*\.(?<my>[^.]+)\.deb\Z     # Match from '.' until end of string in '.deb'

As I'm using named captures, perl 5.10 or above is needed.

Output:

app2
anything
app5
name4
application
app3a



回答5:


This might work for you:

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


来源:https://stackoverflow.com/questions/10277736/how-to-extract-name-of-file

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