큰따옴표 밖의 모든 공백을 \n으로 바꾸는 방법은 무엇입니까?

큰따옴표 밖의 모든 공백을 \n으로 바꾸는 방법은 무엇입니까?

$variable공백으로 구분된 많은 큰따옴표가 있는 경로가 있습니다.

echo $variable

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

내 변수의 경로 수는 다양할 수 있으며 제어되지 않습니다. 예를 들어 다음 예와 같을 수 있습니다.

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"

\n큰 따옴표 안의 공백을 유지하면서 큰따옴표 밖의 모든 공백을 새 줄( )로 바꾸고 싶습니다 . echo $variable | tr " " "\n"다음과 같은 것을 사용하십시오이것대답은 모든 공백을 새 줄로 바꾸기 때문에 나에게 적합하지 않습니다. 어떻게 해야 합니까?

답변1

요소가 다음과 같은 경우언제나큰따옴표의 경우 quote-space-quote를 quote-newline-quote로 바꿀 수 있습니다.

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

또는 (쉘 매개변수 대체 사용)

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

그러나 배열을 사용하도록 스크립트를 수정할 수 있다면 훨씬 더 간단합니다.

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

관련 정보