Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a file containing a a large number of lines, each of which contains a bunch of numbers which are separated by spaces. I process this data in a pipe in some way, and then I want to collapse the multiple lines into a single line of all the numbers separated by spaces.

Is there a standard command-line utility I can use to do this? It seems like most line-by-line utilities won't mess with the newlines...

share|improve this question
add comment

3 Answers

up vote 8 down vote accepted

That's why you don't use line-by-line utilities for this.

$ tr '\n' ' ' < input.txt > output.txt
share|improve this answer
add comment

pipe the output to xargs

#!/bin/sh -x
while
do
date > temp
ping cp1za >> temp
cat temp | xargs echo
done
Tue Dec 17 18:23:31 UTC 2013 CS V1R12: Pinging host CP1ZA.TMMNA.TMM.TOYOTA.C (150.45.12.22) Ping #1 response took 0.001 seconds.
share|improve this answer
add comment

Even line-by-line utilities can remove all newlines.

sed:

sed ':a;N;$!ba;s/\n/ /g' file

awk:

awk '{printf $0" "}' file

But it's much better to use tr, like @Ignacio Vazquez-Abrams wrote.

share|improve this answer
    
I knew it could be done with sed, but you're right, tr is better. Yet another two-letter unix utility to add to my belt. –  JeremyKun May 30 '12 at 1:14
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.