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?

5
  • printf "%s\n" "${variable[@]}" Commented Jun 29, 2018 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... Commented Jun 29, 2018 at 0:43
  • 1
    How is "$variable" created? Commented Jun 29, 2018 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. Commented Jun 29, 2018 at 1:21
  • I would handle this as CSV data and use a CSV parser with space as the field separator. Commented Jun 29, 2018 at 14:28

1 Answer 1

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"

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.