简体   繁体   English

转义空白字符

[英]Escaping Whitespace character

So, I'm new at using bash script, but I am an experienced programmer in Java. 因此,我是使用bash脚本的新手,但是我是Java方面经验丰富的程序员。 I am trying to evaluate a string, by having it go through a loop that looks at each of its characters. 我正在尝试通过使字符串经过一个循环来查看每个字符来评估字符串。 It then needs to replace all whitespace with a hyphen character ("-"). 然后,它需要用连字符(“-”)替换所有空格。 Here's my code: 这是我的代码:

for a in "${newdirectory[@]}"; do
str="LDAUU_"
str+=$a
echo $str | awk -v ORS="" '{ gsub(/./,"&\n") ; print }' | \
while read char
do
if [[ $char == "whitespacecharacter" ]]
then
str+="-"
else
str+=$char
fi
done

The newdirectory variable is an array of user input, which was initially a single variable that was separated into the newdirectory array using the delimiter ",". newdirectory变量是用户输入的数组,最初是一个单个变量,使用定界符“,”将其分隔为newdirectory数组。 The for loop also continues, but it's irrelevant to this section of the script. for循环也将继续,但是与脚本的这一部分无关。 Also, I would prefer not to restructure my code completely. 另外,我不希望完全重组我的代码。 I need something that just evaluates the "char" variable in the while loop as a whitespace character. 我需要一些可以将while循环中的“ char”变量评估为空格字符的东西。 That's it. 而已。 Thank you. 谢谢。

With bash, you can do it all at once with parameter substitution and pattern matching 使用bash,您可以通过参数替换模式匹配一次完成所有操作

str="i am full of spaces"
dashes="${str//[[:blank:]]/-}"
echo "$dashes"                  # i-am-full-of-spaces

Aside from the manual (referenced above) the BashGuide and BashFAQ are good resources for bash programming. 除了手册(上面已提及)外, BashGuideBashFAQ是进行bash编程的好资源。

I hear you, you don't want to "restructure your code completely". 我听说您,您不想“完全重组代码”。 But changing your 5-line for/while imbrication for something a lot more readable won't qualify as "complete restructure". 但是,将5行换为/同时使记忆更加易读时,将不会被视为“完全重组”。

It's really simple in bash to replace all spaces with a dash , given a variable str , just do: 在bash中,给定变量str ,用破折号替换所有空格非常简单,只需执行以下操作:

str=${str// /-}

That will replace all occurences of ' ' with '-' . 那将用'-'代替所有''的出现。

People tend to use auxiliary tools like tr, awk and sed where bash can do the same job faster and with cleaner code, check out : http://wiki.bash-hackers.org/syntax/pe 人们倾向于使用辅助工具,例如tr,awk和sed,在这些工具中bash可以更快地完成相同的工作,并且代码更简洁,请查看: http : //wiki.bash-hackers.org/syntax/pe

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM