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?

  • printf "%s\n" "${variable[@]}" – jasonwryan Jun 29 '18 at 0:33
  • @jasonwryan Thanks for replying. But for some reason this command is just replacing the last character from the line, it's not replacing the spaces in the middle... – Rafael Muynarsk Jun 29 '18 at 0:43
  • 1
    How is "$variable" created? – jasonwryan Jun 29 '18 at 0:47
  • @jasonwryan The steeldriver answer solved the problem. I was actually testing on the terminal declaring it with variable="\"path1\" \"path2\" \"path3\""... But now I see that it needs to be declared as an array to make it work with the printf. – Rafael Muynarsk Jun 29 '18 at 1:21
  • I would handle this as CSV data and use a CSV parser with space as the field separator. – glenn jackman Jun 29 '18 at 14:28
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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.