如何提取文件名?

时间:2012-04-23 09:15:12

标签: linux sed filenames

在目录中,我有一些类似的文件;

org.coy。的应用 _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.的任何的.deb

我只需要粗体名称。

这是我到目前为止所拥有的;

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

5 个答案:

答案 0 :(得分:2)

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

输出

app2
anything
app5
name4
application
app3a

答案 1 :(得分:0)

最好的解决方案是使用带有适当选项的dpkg-query。查看For more information

答案 2 :(得分:0)

您可以使用basename命令使事情变得更容易

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

答案 3 :(得分:0)

使用perl的一种方式:

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

正则表达式的解释:

(?                          # 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'

由于我正在使用命名捕获,因此需要perl 5.10或更高版本。

输出:

app2
anything
app5
name4
application
app3a

答案 4 :(得分:0)

这可能对您有用:

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