views:

85

answers:

5

Most command-line programs just operate on one line at a time.

Can I use a common command-line utility (echo, sed, awk, etc) to concatenate every set of two lines, or would I need to write a script/program from scratch to do this?

$ cat myFile
line 1
line 2
line 3
line 4

$ cat myFile | __somecommand__
line 1line 2
line 3line 4
+2  A: 
$ awk 'ORS=(NR%2)?" ":"\n"' file
line 1 line 2
line 3 line 4

$ paste - -  < file
line 1  line 2
line 3  line 4
ghostdog74
+1 for paste. Note, the default delimiter is tab, use `-d""` if you truly want your lines smashed together.
glenn jackman
A: 

Not a particular command, but this snippet of shell should do the trick:

cat myFile | while read line; do echo -n $line; [ "${i}" ] && echo && i= || i=1 ; done
kanaka
UUOC. `while read line; do echo -n $line; [ "${i}" ] done < File`
ghostdog74
Heh, I wasn't familiar with UUOC until you posted that. For simple cases, I still think cat is clearer even if it's slightly slower and wastes a process. :-)
kanaka
clearer? what is not so clear about input redirection? :)
ghostdog74
Like to have the subject (input) first English speakers do.
kanaka
+4  A: 
sed 'N;s/\n/ /;'

Grab next line, and substitute newline character with space.

seq 1 6 | sed 'N;s/\n/ /;'
1 2
3 4
5 6
Didier Trosset
OT, but use `seq 1 6` in place of your `echo` command.
glenn jackman
@glenn: Thanks. Always something new to learn in UNIX ...
Didier Trosset
`printf "%s\n" {1..6} | sed 'N;s/\n/ /;'`.
ghostdog74
+1  A: 

You can also use Perl as:

$ perl -pe 'chomp;$i++;unless($i%2){$_.="\n"};' < file
line 1line 2
line 3line 4
codaddict
Any tips on making this one-liner shorter are welcome :)
codaddict
`perl -ne 'chomp($p=$_); $q=<>; print $p,$q' file`
glenn jackman
@glenn: That is neat. Thanks.
codaddict
+1  A: 

Here's a shell script version that doesn't need to toggle a flag:

while read line1; do read line2; echo $line1$line2; done < inputfile
Dennis Williamson