linux - Bash - 重命名其中有“的文件

标签 linux bash shell file

好的,我有一个函数,它将一个字符串作为参数,它会输出一个新字符串没有任何< strong>空格, ', "

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//[\"\' ]/}

参见 Parameter Expansion在 Bash 手册中了解此语法的解释。

关于linux - Bash - 重命名其中有“的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46671499/

相关文章:

json - sed 命令不选择值

shell - FreeBSD pkg_create 如何

linux - Grepping 并仅在发现内容时发送电子邮件

mysql - MySQL如何生成MD5加密密码?

Bash:从包含完整路径的读取行中提取用户路径 (/home/userID) 并替换为 "~"

bash - 如何在bash中杀死后抑制终止消息?

bash - 或者 Solaris 中 Shell 脚本中的条件

linux - 如何在不调用其路径的情况下执行 bash 脚本?

java - JNI : NO at openCV install under Linux

linux - 如何在 Bash 中获取文件的绝对目录?