Bash - 重命名文件,其中包含"

Rom*_* B. 3 linux bash shell file

好吧,我有一个功能,将有作为参数字符串,它会输出一个新的字符串具有任何的空间,',"

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
}
Run Code Online (Sandbox Code Playgroud)

但我无法测试char是否"因为它不起作用.如果我打电话给我的功能

rename_file (file"n am_e)
Run Code Online (Sandbox Code Playgroud)

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

Bar*_*mar 5

将名称放在单引号中.

rename_file 'file"n am_e'
Run Code Online (Sandbox Code Playgroud)

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

rename_file "file'n am_e"
Run Code Online (Sandbox Code Playgroud)

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

rename_file "file'na \"me"
Run Code Online (Sandbox Code Playgroud)

另一种选择是使用变量:

quote='"'
rename_file "file'na ${quote}me"
Run Code Online (Sandbox Code Playgroud)

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

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

new_string=${string_to_change//[\"\' ]/}
Run Code Online (Sandbox Code Playgroud)

有关此语法的说明,请参阅Bash手册中的参数扩展.

  • 我怀疑OP实际上并不想要文件名中的parens,并且指出函数调用中不需要它们可能会有所帮助. (2认同)