linux sed 复制,sed命令实现多行复制

以nginx.conf为例。文件原内容为:[root@RS1 conf]# cat nginx.conf

worker_processes  1;

events {

worker_connections  1024;

}

http {

include       mime.types;

default_type  application/octet-stream;

sendfile        on;

keepalive_timeout  65;

server {

listen       80;

server_name  localhost;

location / {

root   html;

index  index.html index.htm;

}

error_page   500 502 503 504  /50x.html;

location = /50x.html {

root   html;

}

}

}

实现复制多个server容器sed -rn 'p;10,21H;21{g;p};21{g;s/^\n//;p}' nginx.conf

sed -rni 'p;10,21H;21{g;p};21{g;s/^\n//;p}' nginx.conf

[root@RS1 conf]# cat nginx.conf

worker_processes  1;

events {

worker_connections  1024;

}

http {

include       mime.types;

default_type  application/octet-stream;

sendfile        on;

keepalive_timeout  65;

server {

listen       80;

server_name  localhost;

location / {

root   html;

index  index.html index.htm;

}

error_page   500 502 503 504  /50x.html;

location = /50x.html {

root   html;

}

}

server {

listen       80;

server_name  localhost;

location / {

root   html;

index  index.html index.htm;

}

error_page   500 502 503 504  /50x.html;

location = /50x.html {

root   html;

}

}

server {

listen       80;

server_name  localhost;

location / {

root   html;

index  index.html index.htm;

}

error_page   500 502 503 504  /50x.html;

location = /50x.html {

root   html;

}

}

}

参考:

多行文本复制,如何用sed或awk或别的工具实现

有文本aaa

bbb

ccc

ddd

eee

匹配bbb-ddd后复制,变为:aaa

bbb

ccc

ddd

bbb

ccc

ddd

eee

使用命令为:sed -rn 'p;/bbb/,/ddd/H;/ddd/{g;s/^\n//;p}' file.txt

说明:

sed内部有两个空间,一个模式空间,一个保留空间。

通常sed将文本内容逐行读入模式空间进行处理,保留空间仅用于暂时保留内部数据用于与模式空间的数据交换。可以这么理解:模式空间用于与外部的数据交换,保留空间用于sed内部的数据交换,最终还是要通过模式空间输出。

/bbb/,/ddd/H;  逐行处理时将bbb~ddd区段的文本从sed的模式空间附加到保留空间内,每行内容之间以\n分割,因此,最终保留空间内容为:\nbbb\nccc\nddd

/ddd/{g;s/^\n//;p}  处理到ddd这行后,通过g命令获取保留空间内容到模式空间,通过s替换命令去除开头的\n,p命令打印。

sed除了可以将输出重定向到新文件外,加 -i 选项还可以直接改写原文件。

其他回答(此处暂时不理解)awk '{print $0;}n ~/1/{a=a"\n"$0;}/^bbb/{a=$0;n=1;}/^ddd/{print a;n=0;}' file_name

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值