微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

linux – Bash – 重命名文件,里面有“

好的我有一个函数,它将作为参数一个字符串,它将输出一个没有任何空格的新字符串,’,“

function rename_file() {

local string_to_change=$1
local length=${#string_to_change}
local i=0   
local new_string=" "
local charac

for i in $(seq $length); do
    i=$((i-1))
    charac="${string_to_change:i:1}"

    if [ "$charac" != " " ] && [ "$charac" != "'" ] && [ "$charac" != """ ];  then #Here if the char is not" ", " ' ", or " " ", we will add this char to our current new_string and else, we do nothing

        new_string=$new_string$charac #simply append the "normal" char to new_string

    fi

done

echo $new_string #Just print the new string without spaces and other characters
}

但我无法测试char是否“因为它不起作用.而且如果我调用我的函数

rename_file (file"n am_e)

它只是打开>并等待我输入一些东西..任何帮助?

解决方法:

名称放在单引号中.

rename_file 'file"n am_e'

如果你想测试单引号,请用双引号括起来:

rename_file "file'n am_e"

要测试它们,将它们放在双引号中并转义内部双引号:

rename_file "file'na \"me"

另一种选择是使用变量:

quote='"'
rename_file "file'na ${quote}me"

此外,您不需要在shell函数的参数周围加上括号.它们被称为普通命令,参数在同一命令行上用空格分隔.

并且您不需要该循环来替换字符.

new_string=${string_to_change//[\"\' ]/}

有关此语法的说明,请参阅Bash手册中的Parameter Expansion.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐