shell 交换、删除记录


有个文件,里面有上万条记录,每条记录的格式如下:

   
  LOG {
  
action: ACCEPT
domain: xxx.net
time: 2012/9/19 15:30
desc: .....
.... #省略不固定的若干行
};

但是每条记录都没有记录号。。
请问:
1.如何删除文件中的第N条记录?
2.如何交换指定的第x条和第y条记录?

sed shell

beat@it 12 years, 1 month ago

我来挖下坟。既然是发在sed话题下,我就试下用sed来处理。

现在只想到一个不成熟的方法,需要用到一个临时文件,效率相当低下。

   
  $ cat LOG
  
LOG {
action: ACCEPT
domain: xxx.net
time: 2012/9/19 15:30
desc: xxx.xxx.xxx.xxx
data: ooooo
data: oooo
};
LOG {
action: ACCEPT
domain: xxx.net
time: 2012/9/19 15:31
desc: xxx.xxx.xxx.xxx
data: ooooo
data: oooo
data: ooo
};
LOG {
action: ACCEPT
domain: xxx.net
time: 2012/9/19 15:32
desc: xxx.xxx.xxx.xxx
data: ooooo
data: oooo
};
LOG {
action: ACCEPT
domain: xxx.net
time: 2012/9/19 15:33
desc: xxx.xxx.xxx.xxx
data: ooooo
};
LOG {
action: ACCEPT
domain: xxx.net
time: 2012/9/19 15:34
desc: xxx.xxx.xxx.xxx
data: ooooo
data: oooo
};

要借助一个临时文件

   
  $ sed '/LOG {/{{:a;N;/}\;/!ba};s/\n/####/g}' LOG > tmp.file
 

比如说删除第3个记录

   
  $ sed -e 's/####/\n/g' -e '3d' tmp.file > LOG
  
$ cat LOG
LOG {
action: ACCEPT
domain: xxx.net
time: 2012/9/19 15:30
desc: xxx.xxx.xxx.xxx
data: ooooo
data: oooo
};
LOG {
action: ACCEPT
domain: xxx.net
time: 2012/9/19 15:31
desc: xxx.xxx.xxx.xxx
data: ooooo
data: oooo
data: ooo
};
LOG {
action: ACCEPT
domain: xxx.net
time: 2012/9/19 15:33
desc: xxx.xxx.xxx.xxx
data: ooooo
};
LOG {
action: ACCEPT
domain: xxx.net
time: 2012/9/19 15:34
desc: xxx.xxx.xxx.xxx
data: ooooo
data: oooo
};

交换第3行和第4行

   
  $ sed -e '3{h;d};4{G}' -e 's/####/\n/g' tmp.file > LOG
  
$ cat LOG
LOG {
action: ACCEPT
domain: xxx.net
time: 2012/9/19 15:30
desc: xxx.xxx.xxx.xxx
data: ooooo
data: oooo
};
LOG {
action: ACCEPT
domain: xxx.net
time: 2012/9/19 15:31
desc: xxx.xxx.xxx.xxx
data: ooooo
data: oooo
data: ooo
};
LOG {
action: ACCEPT
domain: xxx.net
time: 2012/9/19 15:33
desc: xxx.xxx.xxx.xxx
data: ooooo
};
LOG {
action: ACCEPT
domain: xxx.net
time: 2012/9/19 15:32
desc: xxx.xxx.xxx.xxx
data: ooooo
data: oooo
};
LOG {
action: ACCEPT
domain: xxx.net
time: 2012/9/19 15:34
desc: xxx.xxx.xxx.xxx
data: ooooo
data: oooo
};

万花机关小猪 answered 12 years, 1 month ago

Your Answer