Shell通过Args删除文件扩展名

时间:2012-12-20 07:08:46

标签: shell

我希望通过将扩展类型作为参数来删除文件夹中的文件扩展名。

下面是我的代码,它没有按照我的预期工作。

if [ $# -ne 1 ]
then
    echo -e "\nUsage: $0 Ext"
    echo -e "\nExt - Refers to the extension you want to remove"
    echo -e "\nExample1: $0 .txt\nExample2: $0 .doc\nExample3: $0 .pdf\n"
exit 1
fi

ext=$1

for i in *$ext
do
    echo $i
    filename=${i%\$ext}
    echo $i
done

3 个答案:

答案 0 :(得分:0)

您的代码几乎是正确的,但您需要删除转义并回显文件名。下面的代码还显示了basename的使用:

for i in *$ext
do
    echo $i
    filename1=${i%$ext}
    filename2=$(basename $i $ext)
    echo $filename1
    echo $filename2
done

答案 1 :(得分:0)

您可以使用此脚本替换扩展程序

#!/bin/bash

if [ $# -ne 1 ]
then
    echo -e "\nUsage: $0 Ext"
    echo -e "\nExt - Refers to the extension you want to remove"
    echo -e "\nExample1: $0 .txt\nExample2: $0 .doc\nExample3: $0 .pdf\n"
exit 1
fi

ext=$1

for i in *$ext
do
    echo $i
    new_name=`echo $i | sed 's/.'$ext'//g'`
    echo $new_name
done

答案 2 :(得分:0)

您可以使用以下代码:

#!/bin/bash

if [ $# -ne 1 ]

then

    echo -e "\nUsage: $0 Ext"
    echo -e "\nExt - Refers to the extension you want to remove"
    echo -e "\nExample1: $0 .txt\nExample2: $0 .doc\nExample3: $0 .pdf\n"

exit 1
fi

ext=$1

for i in *$ext
do    
    echo $i

    new_name=`echo $i |rev|cut -d'.' -f2-|rev

    echo $new_name
done