【发布时间】:2017-03-03 20:35:40
【问题描述】:
我有一个文本文件,其中包含许多用空格分隔的单词(字符串)。如何用换行符替换空格。换句话说,我怎样才能在bash 中将每个字符串放在不同的行上?如果有人也可以建议一种使用sed 的方法,我将不胜感激!
【问题讨论】:
我有一个文本文件,其中包含许多用空格分隔的单词(字符串)。如何用换行符替换空格。换句话说,我怎样才能在bash 中将每个字符串放在不同的行上?如果有人也可以建议一种使用sed 的方法,我将不胜感激!
【问题讨论】:
一个文件bla:
a b c d e
使用 sed:
sed 's/\s\+/\n/g' bla
结果:
a
b
c
d
e
【讨论】:
使用命令:
sed -i.bak -e 's/\s\+/\n/g' file
\s 将匹配任何空白字符(空格、制表符、换行符),\+ 将匹配连续出现的一个或多个。 -i.bak 会将您的原始文件备份到file.bak。
【讨论】:
$ cat foo
a b c
1 2 3
在 Gnu awk(和 mawk)中:
$ awk -v RS=" +|\n" '{print $0}' foo
a
b
c
1
2
3
将tr 用于单行:
$ tr -s \ '\n' <<< "a b c"
a
b
c
【讨论】:
更多方法:
$ cat ip.txt
foo bar baz
a 433 5er
cat fog try
使用xargs
$ xargs -n1 < ip.txt
foo
bar
baz
a
433
5er
cat
fog
try
使用grep
$ grep -o '[^ ]*' ip.txt
foo
bar
baz
a
433
5er
cat
fog
try
【讨论】:
如果 Perl 是一个选项:
echo "a b c d e" | perl -pe 's/\s+/\n/g'
【讨论】: