Bash - 重命名有“”的文件

3

好的,我有一个函数,它的参数是一个字符串,它将输出一个没有任何空格、'"新字符串

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)吗? - Matias Barrios
如果您键入(或放入脚本中)rename_file(file"n ame),那么您并没有使用参数file"n ame调用函数rename_file。相反,您输入了一个字符串的开头,Bash正在提示您并等待您终止该字符串。请尝试rename_file file\"n ame - William Pursell
不确定您是否想要一个纯Bash解决方案,但我可以建议使用一行代码代替:)new_string=$(echo $string | sed -e 's/ //' -e 's/,//' -e 's/"//')。此外,请将 $1 更改为 ${@} 作为函数参数,否则它会在空格处中断。 - favoretti
是的Matias,这个可以工作,但目标是从存储库中检索文件名并更正此名称。因此,我将调用此函数:rename_file(filename) - Rom
favoretti它不起作用,因为部分's /,//'正在替换,,如果我想使用它来替换',它会打开相同的>并等待我输入东西。 - Rom
1个回答

5
将名称放在单引号中。
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手册中的参数展开部分,了解这种语法的解释。您可以点击此处查看:Shell Parameter Expansion

2
我怀疑 OP 实际上不想在文件名中使用括号,指出在函数调用中不需要它们可能会有所帮助。 - William Pursell
谢谢!我该如何定义一个文件名,例如:fi'le na"me来进行测试?因为如果我像这样输入:"fi'l'e na"me",它会将3个引号视为一体,并打开>等待我输入内容。而且如果我像这样输入:'fi'le na"me',它也会将3个引号视为一体,并打开>等待我输入内容。 - Rom
我无法在其中放入 \",因为它是一个文件名,所以它没有这个 \" - Rom
非常感谢!这正是我在寻找的东西。谢谢。 - Rom
1
为什么你不能这样做?反斜杠并不在实际的文件名中,它只是你在 shell 中输入的方式。 - Barmar
显示剩余7条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接