Linux command to copy file contents one word per line into a new file created from the same command

Viewed 55

I need to copy the file contents one word per line into a new file created from the same command.

This is the file:

Never
gonna
give you up
Never
gonna
let you down
Never
gonna
turn around and desert you

Command already tried:

cat a6q4-input.txt >> a6q4-pt2.txt

This copies the file to newly created file a6q4-pt2.txt in exact format however does not changes the layout of the word content to one word per line.

3 Answers

You can use tr to replace spaces with newlines:

tr ' ' '\n' < input.txt > output.txt

Perl one-liner:

perl -lne 'print for split' a6q4-input.txt > a6q4-pt2.txt

For each line of the files given on the command line (-n), split it up into words based on whitespace with split, and print each one on its own line with print. -l adds a newline after each print (And strips them from each line when read).

Use xargs:

cat in_file | xargs -n1 > out_file

Or use a Perl one-liner:

perl -lane 'print for @F' in_file > out_file

The Perl one-liner uses these command line flags:
-e : Tells Perl to look for code in-line, instead of in a file.
-n : Loop over the input one line at a time, assigning it to $_ by default.
-l : Strip the input line separator ("\n" on *NIX by default) before executing the code in-line, and append it when printing.
-a : Split $_ into array @F on whitespace or on the regex specified in -F option.

SEE ALSO:
perldoc perlrun: how to execute the Perl interpreter: command line switches

Related