如何在输入中用换行符替换空格:
/path/to/file /path/to/file2 /path/to/file3 /path/to/file4 /path/to/file5 等等...
要获得以下内容:
/path/to/file
/path/to/file2
/path/to/file3
/path/to/file4
/path/to/file5
注意
我正在发布此问题以帮助其他用户,在我开始键入此问题之前,要在UNIX SE上找到有用的答案并不容易。之后,我发现了以下内容:
如何在输入中用换行符替换空格:
/path/to/file /path/to/file2 /path/to/file3 /path/to/file4 /path/to/file5 等等...
要获得以下内容:
/path/to/file
/path/to/file2
/path/to/file3
/path/to/file4
/path/to/file5
我正在发布此问题以帮助其他用户,在我开始键入此问题之前,要在UNIX SE上找到有用的答案并不容易。之后,我发现了以下内容:
Answers:
使用tr命令
echo "/path/to/file /path/to/file2 /path/to/file3 /path/to/file4 /path/to/file5"\
| tr " " "\n"
在http://www.unix.com/shell-programming-scripting/67831-replace-space-new-line.html上找到
tr!
在这种情况下,我将使用printf:
printf '%s\n' /path/to/file /path/to/file2 /path/to/file3 /path/to/file4 /path/to/file5
如果其中一个路径内有空格,则可以引用该文件路径,以防止在空格上将其分割:
printf '%s\n' /path/to/file '/path/to/file with spaces' /path/to/another/file
总体而言,对文本进行转换tr是您最好的选择,如现有答案所述。
假设您有一个以空格为分隔符的字符串:
newline_separated=${space_separated// /$'\n'}
但是,您可能会问错问题。(不一定,例如,这可能会在makefile中出现。)用空格分隔的文件名列表实际上并不起作用:如果其中一个文件名包含空格,该怎么办?
如果程序接收文件名作为参数,请不要使用空格将它们连接在一起。用于"$@"一一访问它们。尽管echo "$@"打印的参数之间带有空格,但这是由于echo:它打印的参数带有空格作为分隔符。somecommand "$@"将文件名作为单独的参数传递给命令。如果要在单独的行上打印参数,则可以使用
printf '%s\n' "$@"
如果您确实有用空格分隔的文件名,并且希望将它们放在数组中以对其进行处理,则可以使用不带引号的变量扩展来拆分字符上的值IFS(您需要使用禁用通配符扩展set -f,否则使用glob模式将在值中扩展):
space_separated_list='/path/to/file1 /path/to/file2 /path/to/file3'
IFS=' '; set -f
eval "array=(\$space_separated_list)"
for x in "${array[@]}"; do …
您可以将其封装在一个函数中,该函数可以还原-f设置和设置IFS完成后的值:
split_list () {
local IFS=' ' flags='+f'
if [[ $- = *f* ]]; then flags=; fi
set -f
eval "$1=($2)"
set $flags
}
split_list array '/path/to/file1 /path/to/file2 /path/to/file3'
for x in "${array[@]}"; do …
IFS在本地设置不会生效
这是我的做法:
echo "/path/to/file /path/to/file2 /path/to/file3 /path/to/file4 /path/to/file5" | sed 's/ /\
'/g
注意sed命令中反斜杠后使用Enter键。
sed过tr?
sed因为它是编辑器,而不是简单地翻译字符。
sed可以做更多的事情,但这完全是矫kill过正。tr是完成此工作的正确工具,但是sed稍后会更方便地了解和正则表达式!
echo word1 word2 ... | sed -e 'y/ /\n/;P;D'
是将单行分隔的单词转换为换行符的另一种方法。
以下脚本易于理解且易于使用。
cat filename | tr ' ' '\n' | tee filename
tr)的实质与接受的答案相同。除了您的答案还有以下问题:a)该命令没有缩进4个空格(-> markdown布局)b)您的使用cat是无用的(可以将其替换为< filename tr ' ' '\n')。c)您的输出文件名与输入文件名相同。这样您就可以创建数据竞赛。