如何将文本文件的每两行与 Bash 配对?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1513861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I pair every two lines of a text file with Bash?
提问by fwaechter
With a simple bash script I generate a text file with many lines like this:
使用一个简单的 bash 脚本,我生成了一个包含多行的文本文件,如下所示:
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?
回答by Tim
$ sed '$!N;s/\n/ /' infile
192.168.1.1 hostname1
192.168.1.2 hostname2
192.168.1.3 hostname3
回答by Jukka Matilainen
Here's a shell-only alternative:
这是一个仅限 shell 的替代方案:
while read first; do read second; echo "$first $second"; done
回答by rob
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

