2015-09-10 23 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 

编号现在会改变,将是连续的。