开发者

Concatenate Lines in Bash

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开发者_StackOverflow 4


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


$ awk 'ORS=(NR%2)?" ":"\n"' file
line 1 line 2
line 3 line 4

$ paste - -  < file
line 1  line 2
line 3  line 4


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


You can also use Perl as:

$ perl -pe 'chomp;$i++;unless($i%2){$_.="\n"};' < file
line 1line 2
line 3line 4


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜