我在Linux服务器上的文本文件中有以下记录-
telephone = 1111
a=1
b=2
telephone = 2222
a=1
b=2
c=3
telephone = 3333
a=1
b=2
c=3
d=4
我需要它是这样的-
telephone = 1111, a=1, b=2
telephone = 2222, a=1, b=2, c=3
telephone = 3333, a=1, b=2, c=3, d=4
Grep或perl命令都可以,只要可以帮助获得结果。
使用perl一行代码:
perl -ne 'chomp; print !/^telephone/ ? ", " : $. > 1 ? "n" : ""; print' file.txt
交换机:
-
-n
:为输入文件中的每一行创建一个while(<>){...}
循环。 -
-e
:告诉perl
在命令行上执行代码。
假设您在input.txt
文件中有输入,请尝试以下操作:
perl -ne 'chomp; print /^telephone/ ? "n$_" : ", $_" } { print "n"' input.txt
编辑:防止换行符出现在开头:
perl -ne 'chomp; print !/^telephone/ ? ", $_" : $. > 1 ? "n$_" : "$_" } { print "n"' input.txt
这也可以通过awk:
方便地完成awk 'NR == 1 { buf = $0; next } /^telephone/ { print buf; buf = $0; next } { buf = buf ", " $0 } END {print buf}' input.txt
这个单行代码可以进一步缩短,但是…
EDIT:是的,它可以,考虑到awk从字符串构建布尔值的方式:
awk '/^telephone/ { if(buf) print buf; buf = $0; next } { buf = buf ", " $0 } END {print buf}' input.txt
EDIT2:我添加了我的sed解决方案,它不需要在ooga的解决方案中看到的肢体扭曲:
sed -f myscript input.txt
其中myscript
如下:
#n
/^telephone/ {
x
s/n/, /gp
g
n
}
H
$ {
g
s/n/, /gp
}
即使sed
也能做到这一点。
sed '
$ {H; b output}
{
s/telephone/&/
t output
H
d
: output
x
s/n/, /g
}
1d
' file