transform several lines in one with Awk

awk ' { printf ("%s ", $0)} END {printf ("\n") } ' FILE
remove all carriage return of a given file (or input, if used with | ) and replace them with a space (or whatever character is after %s)
Sample Output
[user@server ~]$ cat tmp-file
line 2
line  3
[user@server ~]$ awk ' { printf ("%s ", $0)} END {printf ("\n") } ' tmp-file
line1 line 2 line  3

# if the file is in MS-DOS format, use dos2nuix to convert it to unix format (or ":set ff=unix" in vim)
[thomas@tom-linux:2 ~]$ cat tmp-file
line  1
line 2
line 4
[thomas@tom-linux:2 ~]$ awk ' { printf ("%s", $0)} END {printf ("\n") } ' tmp-file
line 41
[thomas@tom-linux:2 ~]$ vi tmp-file ^C
[thomas@tom-linux:2 ~]$ dos2unix tmp-file
dos2unix: converting file tmp-file to UNIX format ...
[thomas@tom-linux:2 ~]$ awk ' { printf ("%s", $0)} END {printf ("\n") } ' tmp-file
line  1 line 2 line3 line 4

By: bouktin
2011-02-02 11:51:41

What Others Think

Personally, I'd go for: paste -sd\ FILE (That's: dash s d backslash space space)
flatcap · 419 weeks and 4 days ago
for simple lists xargs echo < file elaborated, dos files included perl -l40 -pe 's/\r//g' file; echo
forcefsck · 419 weeks and 4 days ago
Here is another way to do it: xargs -d'\n' < FILE perl -lp0777e's/\n/ /g' FILE
seungwon · 419 weeks and 4 days ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this? is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands

Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.


Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: