使用 AWK 将文本文件中的每个单词放在新行上

dat*_*guy 5 bash awk

我正在尝试使用 AWK 将文本文档中的每个单词放在新行上。我真的不知道如何使用 AWK,但我在网上找到了一些命令应该可以解决我的问题。我尝试过以下命令:

$ awk '{ for (i = 1; i <= NF; i++) print $i }' input.txt > output.txt 
Run Code Online (Sandbox Code Playgroud)

$ awk '{c=split($0, s); for(n=1; n<=c; ++n) print s[n] }' input.txt > output.txt
Run Code Online (Sandbox Code Playgroud)

但是,这两个命令具有相同的效果,即删除所有空格。

为了清楚起见,假设 input.txt 包含文本:

The fox jumped over the dog
Run Code Online (Sandbox Code Playgroud)

输出.txt 应包含:

The
fox
jumped
over
the
dog
Run Code Online (Sandbox Code Playgroud)

然而,output.txt 包含:

Thefoxjumpedoverthedog
Run Code Online (Sandbox Code Playgroud)

我在 Windows 7 上使用 Cygwin 来使用这些命令。命令中是否缺少某些内容?

kar*_*kfa 5

另一种选择

echo "the fox jumped over the dog" | awk -v OFS="\n" '{$1=$1}1'
Run Code Online (Sandbox Code Playgroud)

从文件中读取awk ... inputfile

但是,我不确定它会解决您的问题。如果你awk崩溃了你可以尝试tr

echo ... | tr ' ' '\n'
Run Code Online (Sandbox Code Playgroud)

会做。


szy*_*zym 3

根据联机帮助页,print在 awk 中打印其参数:

由当前输出字段分隔符分隔,并由输出记录分隔符终止

所以你的第一个命令是好的,但你需要确保你的输出记录分隔符是一个新行。默认输出记录分隔符是换行符,但请尝试确保:

awk -v ORS='\n' '{ for (i = 1; i <= NF; i++) print $i }' input.txt > output.txt
Run Code Online (Sandbox Code Playgroud)

仅在 Cygwin 上,您可能会遇到 Windows/DOS 行结尾问题。也试试吧ORS='\r\n'。或者,通过管道输出unix2dos