开发者

How do I pair every two lines of a text file with Bash? [duplicate]

This question already has answers here: How to merge every two lines into one from the command line? (21 answers) Closed 6 years ago.

With a simple bash scr开发者_如何学运维ipt I generate a text file with many lines like this:

192.168.1.1
hostname1
192.168.1.2
hostname2
192.168.1.3
hostname3

Now I want to reformat this file so it looks like this:

192.168.1.1 hostname1
192.168.1.2 hostname2
192.168.1.3 hostname3

How would I reformat it this way? Perhaps sed?


$ sed '$!N;s/\n/ /' infile
192.168.1.1 hostname1
192.168.1.2 hostname2
192.168.1.3 hostname3


I love the simplicity of this solution

cat infile | paste -sd ' \n'

192.168.1.1 hostname1
192.168.1.2 hostname2
192.168.1.3 hostname3

or make it comma separated instead of space separated

cat infile | paste -sd ',\n'

and if your input file had a third line like timestamp

192.168.1.1
hostname1
14423289909
192.168.1.2
hostname2
14423289910
192.168.1.3
hostname3
14423289911

then the only change is to add another space in to the delimiter list

cat infile | paste -sd '  \n'

192.168.1.1 hostname1 14423289909
192.168.1.2 hostname2 14423289910
192.168.1.3 hostname3 14423289911


Here's a shell-only alternative:

while read -r first; do read second; echo "$first $second"; done < filname

-r - Do not allow backslashes to escape any characters

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜