7

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...

13

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

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

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.

  • 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
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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