【发布时间】:2019-01-31 02:36:29
【问题描述】:
寻找一种在给定字符串第 N 次出现后插入一行的方法。
以下内容与我要查找的内容接近,但基于行号,而不是基于给定字符串的第 N 次出现。
perl -ni -e 'print; print "Put after fifth line\n" if $. == 5' inFile.txt
【问题讨论】:
-
一行字符串可以多次出现吗?
寻找一种在给定字符串第 N 次出现后插入一行的方法。
以下内容与我要查找的内容接近,但基于行号,而不是基于给定字符串的第 N 次出现。
perl -ni -e 'print; print "Put after fifth line\n" if $. == 5' inFile.txt
【问题讨论】:
如果未启用警告,则无需初始化计数。
perl -pe'$_.="foo\n" if /bar/ && ++$c == 5'
模数 (%) 运算符非常适合检测每 N 个。
perl -pe'$_.="foo\n" if /bar/ && ++$c % 5 == 0'
【讨论】:
[看到有人查看常见问题解答总是很高兴! How do I change, delete, or insert a line in a file, or append to the beginning of a file?.]
我会这样做:
% perl -ni -e 'print; print "Inserted\n" if (/time/ && ++$c) == 3' input.txt
计数器变量$c按匹配运算符的返回值递增。如果不匹配则为 0,如果匹配则为 1(它在标量上下文中使用,因此即使使用 /g,它也最多只匹配一次)。在更新到 $c 之后,它会与您想要的值进行比较。
这是 input.txt:
First time
Second time
Third time
Fourth time
结果:
First time
Second time
Third time
Inserted
Fourth time
或者,您可以使用-p 将其缩短一点,它会自动在末尾添加print。在这种情况下,您最终会在下一行插入 before 行,而不是在上一行插入 after 行(如果您没有足够的行来,这可能是个问题在某事之前):
% perl -pi -e 'print "Inserted\n" if (/time/ && ++$c) == 4' input.txt
而且,如果您还没有使用它,您可以考虑升级到 v5.28。 In-place editing gets a bit safer 首先写入临时文件,然后在程序成功完成后替换源文件。
【讨论】:
Inserted,直到计数器改变......例如,从Fourth time 行中删除time..
-p,当前行的输出在插入之后。这就是为什么我在第二个单行中将数字更改为大一。
如果您希望在字符串每出现五次后重复一次,您可以在 BEGIN 块中创建一个变量并对其进行监控:
perl -n -e 'BEGIN{$c=0;} print; $c++ if /one/; if ($c==5){print "Put after fifth entry\n";$c=0}' inFile.txt
【讨论】:
下面会在字符串abc第二次出现后添加一行xyz:
perl -pi -e '/abc/&&++$n==2 and $_.="xyz\n"' inFile.txt
【讨论】: