1

I have a $variable that has many double quoted paths separated by spaces

echo $variable

"/home/myuser/example of name with spaces" "/home/myuser/another example with spaces/myfile"

The number of paths on my variable can vary and it's not something under control. It can e.g. be like the following examples:

example 1: "path1" "path2" "path3" "path4"
example 2: "path1" "path2" "path3" "path4" "path5" "path6" path7" "path8"
example 3: "path1" "path2" "path3" 
example 4: "path1" "path2" "path3" "path4" "path5" "path6"

I want to replace all spaces outside the double quotes into a new line (\n) while preserving the spaces that are inside quotes. Using echo $variable | tr " " "\n" like in this answer doesn't work for me because it replaces all the spaces by new lines. How can I do it?

1 Answers1

2

If the elements are always double quoted, then you can replace quote-space-quote with quote-newline-quote:

$ sed 's/" "/"\n"/g' <<< "$variable"
"/home/myuser/example of name with spaces"
"/home/myuser/another example with spaces/myfile"

or (using shell parameter substitution)

$ printf '%s\n' "${variable//\" \"/\"$'\n'\"}"
"/home/myuser/example of name with spaces"
"/home/myuser/another example with spaces/myfile"

But it would be simpler if you can modify your script to use an array:

$ vararray=("/home/myuser/example of name with spaces" "/home/myuser/another example with spaces/myfile")
$ printf '"%s"\n' "${vararray[@]}"
"/home/myuser/example of name with spaces"
"/home/myuser/another example with spaces/myfile"
steeldriver
  • 81,074