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

て烟熏妆下的殇ゞ 提交于 2019-12-20 10:18:25

问题


With a simple bash script 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?


回答1:


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



回答2:


Here's a shell-only alternative:

while read first; do read second; echo "$first $second"; done



回答3:


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


来源:https://stackoverflow.com/questions/1513861/how-do-i-pair-every-two-lines-of-a-text-file-with-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!