如何将文件中的行按2分组?


9

我有一个这样的文本文件:

a
b
c
d
e
f
g

我如何将这些行分组以获得这样的输出:

a-b
b-c
c-d
d-e
e-f
f-g

我必须在shell(sh,csh,bash)中执行此操作。

我发现了这一点:

cat file | xargs -n2

但第一组的最后一个元素没有成为第二个的第一个。

Answers:


9

awk

awk 'NR!=1{print x"-"$0}{x=$0}' file
  • NR!=1 适用于所有行,第一个除外
  • print x"-"$0 打印之间的破折号值
  • x=$0设置x(用于下一次迭代)


5
paste -d- - ./infile <infile

^这将非常有效,只不过您的输入是一对一的。所以...

{ echo; cat <infile; } | paste -d- - ./infile | sed '1d;$d'

会工作,但可能太复杂了


好吧,一开始误读了OP要求后,我的想法完全一样,但我决定sed不做任何事情。
cuonglm '16

@cuonglm-我读错了吗?
mikeserv '16

1
不,我敢打赌。但是您需要sed 1d\;\$d更正它。
cuonglm '16

这个变体怎么样?sed '2~2p' infile | paste -d- - -
steeldriver '16

1
现在我明白了。paste -d- <(head -n -1 input) <(tail -n +2 input)
Costas

2

多一个 sed

sed '$!N;s/\n/-/p;s/-/\n/;D' <input

并可以进行修改(感谢mikeserv):

sed -n 'N;y/\n/-/;P;y/-/\n/;D' <input

1
y/-\n/\n-/可以同时替换两个s ///。如果这样做的话,它可以更快,更便于携带和使用。
mikeserv '16

1

一个纯bash版本-

old=""; while read -r line ; do [[ -n "$old" ]] && echo   $old-$line;   old=$line; done  < input

a-b
b-c
c-d
d-e
e-f
f-g
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.