在每个匹配的字符串模式之前放置编号

Xti*_*yro 1 bash shell sed

我需要替换这个:

01:05:01:11 --> 01:05:04:07,so you may continue to support us,|bring us health,
$Italic = True
01:05:04:15 --> 01:05:07:09,well-being,
$Italic = False
01:05:07:21 --> 01:05:13:01,and help us to be one big family|and continue working as a team.
Run Code Online (Sandbox Code Playgroud)

基本上成为这样:

1
01:05:01:11 --> 01:05:04:07,so you may continue to support us,|bring us health,
$Italic = True
2
01:05:04:15 --> 01:05:07:09,well-being,
$Italic = False
3
01:05:07:21 --> 01:05:13:01,and help us to be one big family|and continue working as a team.
Run Code Online (Sandbox Code Playgroud)

EDIT_1:这意味着我需要匹配:

' --> '
Run Code Online (Sandbox Code Playgroud)

并计算其发生率.

EDIT_2:所以,例如,我需要只匹配包含以下内容的行:

01:05:04:15 --> 01:05:07:09,
Run Code Online (Sandbox Code Playgroud)

并且在每个这样的行之前,我需要将上述示例的出现次数插入到文件中.

我想出了这个使用'sed'命令的短Shell脚本,但处理更大的文件需要很长时间(例如,超过60行).

# Define the number of the special chars - so you can calculate the number of the subtitle lines
special_chars_no="$(grep -o ' --> ' Output_File | wc -l)"

# Add numbering before every subtitle line
for ((i=1;i<=${special_chars_no};i++)) ;
do
sed -i '/\([0-9][0-9]\):\([0-9][0-9]\):\([0-9][0-9]\):\([0-9][0-9]\) -->/{:1 ; /\(.*\([0-9][0-9]\):\([0-9][0-9]\):\([0-9][0-9]\):\([0-9][0-9]\) -->\)\{'"${i}"'\}/!{N;b1} ; s/\([0-9][0-9]\):\([0-9][0-9]\):\([0-9][0-9]\):\([0-9][0-9]\) -->/'"${i}"'\n\1:\2:\3:\4 -->/'"${i}"' ; :2 ; n ; $!b2}' Output_File  
done
Run Code Online (Sandbox Code Playgroud)

我们可以让它可用(更快)吗?

Ed *_*ton 6

$ awk '/-->/{print ++cnt} 1' file
1
01:05:01:11 --> 01:05:04:07,so you may continue to support us,|bring us health,
$Italic = True
2
01:05:04:15 --> 01:05:07:09,well-being,
$Italic = False
3
01:05:07:21 --> 01:05:13:01,and help us to be one big family|and continue working as a team.
Run Code Online (Sandbox Code Playgroud)

  • @Sundeep你在perl上花了太多时间:-). (2认同)