Nathaniel Weissinger
Nathaniel Weissinger

Reputation: 45

Escaping Whitespace character

So, I'm new at using bash script, but I am an experienced programmer in 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 ",". The for loop also continues, but it's irrelevant to this section of the script. 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. That's it. Thank you.

Upvotes: 0

Views: 2912

Answers (2)

Gui Rava
Gui Rava

Reputation: 448

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".

It's really simple in bash to replace all spaces with a dash , given a variable str, just do:

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

Upvotes: 3

glenn jackman
glenn jackman

Reputation: 246807

With bash, you can do it all at once with parameter substitution and pattern matching

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.

Upvotes: 3

Related Questions