码迷,mamicode.com
首页 > 其他好文 > 详细

sed命令实现多行复制

时间:2017-04-06 23:44:56      阅读:563      评论:0      收藏:0      [点我收藏+]

标签: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



本文出自 “甘木” 博客,请务必保留此出处http://ganmu.blog.51cto.com/9305511/1913599

sed命令实现多行复制

标签:sed

原文地址:http://ganmu.blog.51cto.com/9305511/1913599

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!