【问题标题】:Bash - Rename file that have " in itBash - 重命名包含“的文件
【发布时间】:2017-10-10 16:23:20
【问题描述】:

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

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

标签: linux bash shell file


【解决方案1】:

将名称放在单引号中。

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

【讨论】:

  • 我怀疑 OP 实际上并不需要文件名中的括号,指出函数调用中不需要它们可能会有所帮助。
  • 啊,这个其实很酷!我自己忘记了扩展,在对 OP 的评论中提供了基于 sed 的解决方案。
  • 谢谢!我怎样才能定义一个文件名:fi'le na"me 来测试?因为如果我这样写:"fi'l'e na"me" 它会考虑 3 " 并将打开 > 并等待我输入一些内容 并且 如果我这样写:@987654331 @ 它会考虑 3 ' 并会打开 > 并会等我输入一些东西
  • 我不能把\"放进去,因为它是一个文件名,所以里面没有\"
  • 你为什么不能这样做?反斜杠不在实际文件名中,它只是您在 shell 中键入的方式。
猜你喜欢
  • 2019-02-20
  • 1970-01-01
  • 2011-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-21
  • 2019-09-04
  • 2012-08-15
相关资源
最近更新 更多