The question on the title: replace space with new line
The simple, quick, brute force solution is to do exactly that, replace all spaces with new lines:
echo "$input" | tr ' ' '\n'
echo "$input" | sed 'y/ /\n/'
echo "$input" | sed 's/ /\n/g'
Filenames
But in your question you are listing a list of paths:
echo '/path/to/file /path/to/file2 /path/to/file3 /path/to/file4 /path/to/file5' > test.txt
Using the solution above will not work for filenames with spaces (or newlines).
Better
But we can use a two characters delimiter: /
(space slash)
That pair of characters could only exist at the beginning of a new (absolute) path:
input='/path/to/file /path/to/file2 /path/to/one space /path/to/new
line /path/to/file5'
$ printf '%s\n' "$input" | sed 's# /#\n/#g'
/path/to/file
/path/to/file2
/path/to/one space
/path/to/new
line
/path/to/file5
For relative paths, we need to also allow paths that start with ./
or ../
:
$ cat test2.txt
/path/to/file /path/to/file2 /path/to/one space /path/to/new
line /path/to/file5 ./path/to/file ../path/to/file2 ./path/to/one space ./path/to/new
line ./path/to/file5 ../path/to/file ../path/to/file2 ../path/to/one space ../path/to/new
line ../path/to/file5
$ sed 's# ([.]{0,2}/)#\n\1#g' test2.txt
/path/to/file
/path/to/file2
/path/to/one space
/path/to/new
line
/path/to/file5
./path/to/file
../path/to/file2
./path/to/one space
./path/to/new
line
./path/to/file5
../path/to/file
../path/to/file2
../path/to/one space
../path/to/new
line
../path/to/file5
Best
For path names with newlines it is better to quote each pathname.
$ sed -e '1s/^/"/' -e 's# \([.]\{0,2\}/\)#"\n"\1#g' -e '$s/$/"/' test2.txt
"/path/to/file"
"/path/to/file2"
"/path/to/one space"
"/path/to/new
line"
"/path/to/file5"
"./path/to/file"
"../path/to/file2"
"./path/to/one space"
"./path/to/new
line"
"./path/to/file5"
"../path/to/file"
"../path/to/file2"
"../path/to/one space"
"../path/to/new
line"
"../path/to/file5"
/User/myself/VirtualBox VMs/
. – Kusalananda Feb 14 '21 at 22:33