如何为每行末尾的数字添加值

2 投票
9 回答
535 浏览
提问于 2025-04-16 13:42

假设有一些来自文件的文本:

(bookmarks
("Chapter 1 Introduction 1" "#1"
("1.1 Problem Statement and Basic Definitions 2" "#2")
("1.2 Illustrative Examples 4" "#4")
("1.3 Guidelines for Model Construction 26" "#26")
("Exercises 30" "#30")
("Notes and References 34" "#34"))
)

如果每行的最后面有一个数字,我该如何在这个数字上加11呢,比如说:

(bookmarks
("Chapter 1 Introduction 1" "#12"
("1.1 Problem Statement and Basic Definitions 2" "#13")
("1.2 Illustrative Examples 4" "#15")
("1.3 Guidelines for Model Construction 26" "#37")
("Exercises 30" "#41")
("Notes and References 34" "#45"))
)

可以使用sed、awk、python、perl、正则表达式等等来实现……

谢谢,祝好!

9 个回答

2

在Python中,试试:

import re
m = re.search(r'(?<=#)([0-9]+)',txt)

来找到下一个数字。然后设置:

txt = txt[:m.start()] + str(int(m.group())+11) + txt[m.end():]

只要search没有找到更多匹配项,就重复这个过程(比如用一个while循环)。

注意:这个正则表达式(?<=#)([0-9]+)可以匹配任何在#符号后面的数字序列。start()会给出下一个匹配项的起始位置;end()会给出结束位置,而group()则会返回实际匹配到的内容。表达式str(int(m.group()) + 11)会把匹配到的数字转换为整数,加上11,然后再转换回字符串。

4
use strict;
use warnings;
while(my $line = <DATA>){
  $line =~ s/#(\d+)/'#'.($1 + 11)/e;
}
__DATA__
(bookmarks
("Chapter 1 Introduction 1" "#1"
("1.1 Problem Statement and Basic Definitions 2" "#2")
("1.2 Illustrative Examples 4" "#4")
("1.3 Guidelines for Model Construction 26" "#26")
("Exercises 30" "#30")
("Notes and References 34" "#34"))
)

输出:

(bookmarks
("Chapter 1 Introduction 1" "#12"
("1.1 Problem Statement and Basic Definitions 2" "#13")
("1.2 Illustrative Examples 4" "#15")
("1.3 Guidelines for Model Construction 26" "#37")
("Exercises 30" "#41")
("Notes and References 34" "#45"))
)
5
awk -F'#' 'NF>1{split($2,a,"[0-9]+");print $1 FS $2+11 a[2];next}1' infile
$ awk -F'#' 'NF>1{split($2,a,"[0-9]+");print $1 FS $2+11 a[2];next}1' infile
(bookmarks
("Chapter 1 Introduction 1" "#12"
("1.1 Problem Statement and Basic Definitions 2" "#13")
("1.2 Illustrative Examples 4" "#15")
("1.3 Guidelines for Model Construction 26" "#37")
("Exercises 30" "#41")
("Notes and References 34" "#45"))
)

概念验证

撰写回答