fun*_*fun 3 sed text-processing join
我在董事会上找不到这个案例,所以我在问这个问题。
这是输入文件:
module
x(a,b,c)
module
y(d,e,f,
g,h,i)
module
z(j,k,l)
Run Code Online (Sandbox Code Playgroud)
并且输出文件应该是:
module x(a,b,c)
module y(d,e,f,
g,h,i)
module z(j,k,l)
Run Code Online (Sandbox Code Playgroud)
Kus*_*nda 10
您想要做的是将module行与下一行连接起来。
使用sed:
$ sed '/^module/N;s/\n//' file
module x(a,b,c)
module y(d,e,f,
g,h,i)
module z(j,k,l)
Run Code Online (Sandbox Code Playgroud)
这是按原样复制和粘贴的数据,每行末尾都有空格。
该sed命令将在读取时打印每一行,但是当它遇到以 string 开头的行时module,它会在下一行附加一个嵌入的换行符(这就是这样N做的)。在打印结果之前,我们通过替换删除该换行符。
如果您的数据在行尾没有空格,请使用
$ sed '/^module/N;s/\n/ /' file
module x(a,b,c)
module y(d,e,f,
g,h,i)
module z(j,k,l)
Run Code Online (Sandbox Code Playgroud)
以防万一你想要这个(假设输入行末尾没有空格):
$ sed -e '/^module/bpp' -e 'H;$bpp' -e 'd' \
-e ':pp' -e 'x;/^$/d;s/\n/ /g' file
module x(a,b,c)
module y(d,e,f, g,h,i)
module z(j,k,l)
Run Code Online (Sandbox Code Playgroud)
注释sed脚本:
/^module/ b print_previous; # print previous record
H; # append this line to hold space
$ b print_previous; # print previous (last) record
d; # end processing this line
:print_previous; # prints a record accumulated in the hold space
x; # swap in the hold space
/^$/ d; # if line is empty, delete it
s/\n/ /g; # replace embedded newlines by spaces
# (implicit print)
Run Code Online (Sandbox Code Playgroud)