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
}

但我只是无法测试字符是否",因为它不起作用。如果我调用我的函数

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 手册中的参数扩展。

最新更新