【发布时间】: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/,//'部分正在替换,,如果我想用它来替换'它会打开相同的>并等待我输入一件事