2015-09-10 45 views
-3

我試圖在插入或刪除記錄後不斷重新編號文件中的記錄。該文件如下所示,具有> 100條記錄。如果例如第二條記錄被刪除,所有後面的記錄都需要重新編號,以便順序沒有間隔。任何想法如何在例如bash或awk(或perl)......如果它只是在理論上。在列表中連續編號多行記錄

記錄file.txt的:

# filter rule1 
FilterRule1.match_message_facility = MME_E 
FilterRule1.match_message_process = -1 
FilterRule1.match_message_host = -1 
FilterRule1.not_matched_facility_to_log_to = MME_E 
FilterRule1.max_time_since_last_match_secs = 300 


# incoming files 
FilterRule2.match_message_facility = EXG 
FilterRule2.match_message_event_severity = I 
FilterRule2.match_message_host = -1 
FilterRule2.not_matched_facility_to_log_to = EXG 
FilterRule2.max_time_since_last_match_secs = 2000 

# outgoing files 
FilterRule3.match_message_facility = EXG 
FilterRule3.match_message_event_severity = I 
FilterRule3.match_message_host = -1 
FilterRule3.not_matched_facility_to_log_to = EXG 
FilterRule3.max_time_since_last_match_secs = 14400 

# outgoing files: included headers 
FilterRule4.match_message_facility = EXG 
FilterRule4.match_message_event_severity = I 
FilterRule4.match_message_host = -1 
FilterRule4.not_matched_facility_to_log_to = EXG 
FilterRule4.max_time_since_last_match_secs = 900 

... 
+0

這是什麼記錄? – Vijay

+0

和你嘗試失敗(和哪個錯誤)? – NeronLeVelu

+0

CODE在哪裏? – serenesat

回答

2

讀輸入在 「段落模式」,一個記錄的時間。將規則編號更改爲您保留在變量中的值,將其增加爲每條記錄:

#!/usr/bin/perl 
use warnings; 
use strict; 

$/ = '';     # Read in the "paragraph mode". 
my $record_id = 1; 
while (<>) { 
    s/^FilterRule[0-9]+/FilterRule$record_id/gm; 
    $record_id++; 
    print; 
} 
2

awk to rescue!

awk -vRS= -vORS="\n\n" '{gsub(/FilterRule[0-9]*/,"FilterRule"NR)}1' 

對從1開始的記錄連續編號。

+1

評論。 – karakfa

+0

信不信由於''-v'和'var = value'之間沒有放置空格,所以腳本特定於gawk,所以最好在'-v RS = -v ORS ='\ n \ n中放一個空格''所以它可以和任何awk一起工作。 –

0

刪除了第三個記錄:

7> cat temp 
# filter rule1 
Filterrule1.match_message_facility = MME_E 
Filterrule1.match_message_process = -1 
Filterrule1.match_message_host = -1 
Filterrule1.not_matched_facility_to_log_to = MME_E 
Filterrule1.max_time_since_last_match_secs = 300 


# incoming files 
Filterrule2.match_message_facility = EXG 
Filterrule2.match_message_event_severity = I 
Filterrule2.match_message_host = -1 
Filterrule2.not_matched_facility_to_log_to = EXG 
Filterrule2.max_time_since_last_match_secs = 2000 


# outgoing files: included headers 
Filterrule4.match_message_facility = EXG 
Filterrule4.match_message_event_severity = I 
Filterrule4.match_message_host = -1 
Filterrule4.not_matched_facility_to_log_to = EXG 
Filterrule4.max_time_since_last_match_secs = 900 
> 

運行命令:

perl -pi -lne '{$i++ if(/^#/);s/Filterrule./Filterrule$i/g;}' temp 

編號現在會改變,將是連續的。