2017-09-01 113 views
0

我有大的文本文件(471 615行)。它的結構是這樣的:LINUX從文件中刪除文本部分與sed基於

use TABLE1/*!*/ 
good code here 
use mysql/*!*/ 
bad code here 
use TABLE1/*!*/ 
good code here 
use mysql/*!*/ 
... 
... 

如何刪除「錯誤的代碼」部分? Offcourse我知道這將是正則表達式的循環,但如何使它?我已經使用bash循環來從mysql二進制日誌文件中構建類似的文件,並根據它們的行號刪除了一些sed內容,但是這個文件有太多的事件可以通過行號刪除它們。

PS。我剛剛手動完成了1個月的時間,並且出現了23次「錯誤代碼」。有6個月的時間可以修復,所以大概會有130-140次發生。正如你看到的,我將不得不花費整整一天剷除出來手動

+0

錯誤代碼後,每行「使用mysql「排隊第一次」使用TABLE1「 – 180doman

回答

0

我試圖RomanPerekhres和拉曼Sailopal解決方案。第一次剪切得太多了(文件開頭有一些標題,第二個做了很好的工作,但留下了一些問題,我沒有試圖分析原因,只是改變了策略,我只是刪除了每一行,包含一些特定的詞,如GRANT TO, FUNCTION,CREATE USER,DROP USER,特權等(與SED offcourse)。這樣我切出mysql表連接的所有命令。

謝謝大家對你的幫助呢。

1

簡單AWK方法:

示例文件testfile

use TABLE1/*!*/ 
select user_id 
from 
system_users 
use mysql/*!*/ 
drop database 
delete * from users 
delete id from system_users 
use TABLE1/*!*/ 
select 
    sum(price) 
from 
    orders 
use mysql/*!*/ 
update users 
    set id = "bad boy" 
drop table users 

的工作:

awk '/^use TABLE/{ f=1 }/^use mysql/{ print; f=0 }f' testfile 

輸出:

use TABLE1/*!*/ 
select user_id 
from 
system_users 
use mysql/*!*/ 
use TABLE1/*!*/ 
select 
    sum(price) 
from 
    orders 
use mysql/*!*/ 
0

這可能爲你工作(GNU SED):

sed '/^use/h;G;/^use mysql/M!P;d' file 

追加use語句每行,只打印不包含use mysql所附的那些行部分。

0

另一個sed的方法

sed '/use mysql\/*!*\//,/use TABLE1\/*!*\//{//!d}' filename 

搜索使用MySQL之間的一切......和使用TABLE1 ......那麼除了包含搜索模式的行刪除所有內容。

0

sed是s/old/new/,就是這樣。你不是在做s/old/new/所以你不應該考慮使用sed。只需使用AWK:

$ awk '/^use mysql/{f=1} /^use TABLE1/{f=0} !f' file 
use TABLE1/*!*/ 
good code here 
use TABLE1/*!*/ 
good code here 

如果你喜歡打高爾夫球,你可以減少只是:

$ awk '/^use/{f=/mysql/}!f' file 
use TABLE1/*!*/ 
good code here 
use TABLE1/*!*/ 
good code here