简体   繁体   中英

Using AWK to place each word in a text file on a new line

I'm trying to use AWK to place every word within a text document on a new line. I don't really know how to use AWK but I've found some commands online which should solve my problem. I've tried the following commands:

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

and

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

However, both of these commands have the same effect, which is that all spaces are removed.

For clarity, lets say that input.txt contains the text:

The fox jumped over the dog

output.txt should contain:

The
fox
jumped
over
the
dog

However output.txt contains:

Thefoxjumpedoverthedog

I'm using Cygwin on Windows 7 to use these commands. Is there something I'm missing within the commands?

another alternative

echo "the fox jumped over the dog" | awk -v OFS="\n" '{$1=$1}1'

to read from a file awk ... inputfile

however, I'm not sure it will solve your case. If you awk is broken you can try tr

echo ... | tr ' ' '\n'

will do.

According to the manpage, print in awk prints its arguments:

separated by the current output field separator, and terminated by the output record separator

So your first command is ok, but you need to make sure your output record separator is a new line. The default output record separator is a newline, but try making sure:

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

On Cygwin only, you might be running into issue with Windows/DOS line endings. Try also ORS='\\r\\n' . Alternatively, pipe the output through unix2dos .

You can do this trivially in Perl:

$ echo "The fox jumped over the dog" | perl -ple 's/\h/\n/g'
The
fox
jumped
over
the
dog

Same works in awk:

$ echo "The fox jumped over the dog" | awk '{gsub(/ /,"\n"); print}'
The
fox
jumped
over
the
dog

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM