bash Perl / Awk / Sed - 查找和替换数字和自动递增
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23689603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Perl / Awk / Sed - Find and Replace Number & auto-increment
提问by user3642747
I am looking for a perl/awk/sed
command to auto-increment the number in column 7
Example line in file knownfile.txt:
我正在寻找一个perl/awk/sed
命令来自动增加文件 knownfile.txt 中第 7 列示例行中的数字:
The file has formatting and 7 columns.
该文件具有格式和 7 列。
today is a great day and it
is also an amazing day tomorrow now
blahblah foo today build number is 5928
I want to retain all formatting and simply replace 5928
with 5929
and save file
我要保留所有格式,只需更换5928
与5929
和保存文件
I tried:
我试过:
awk '/blahblah/{ ++; print $ cat file
today is a great day and it
is also an amazing day tomorrow now
blahblah foo today build number is 5928
$ awk '{sub(/[[:digit:]]+$/,$NF+1)}1' file
today is a great day and it
is also an amazing day tomorrow now
blahblah foo today build number is 5929
}' filename > tmp && mv tmp filename
It increments the number and I think it retains the formatting, but it only prints the edited line to the file.
它增加了数字,我认为它保留了格式,但它只将编辑过的行打印到文件中。
回答by Ed Morton
perl -i -pe 's/(\d+)$/1+/e' knownfile.txt
If that doesn't do what you want then seriously THINK about what sample input and expected output you're posting as that's all we have to go on.
如果这不能满足您的要求,那么请认真考虑您发布的样本输入和预期输出,因为这就是我们要做的全部工作。
回答by Miller
Using a perl one-liner
使用 perl one-liner
awk '/foo/{++$NF}1' file
回答by Tom Fenech
Given that the number is always at the end of the line, you could do this in awk:
鉴于数字总是在行尾,您可以在 awk 中执行此操作:
awk '/foo/{++$NF}1' file > tmp && mv tmp file
where file
is the file you want to operate on. This simply increments the value of the last column when the line contains the word "foo". The 1
at the end means perform the default action, which is to print the line.
file
你要操作的文件在哪里。当该行包含单词“foo”时,这只会增加最后一列的值。所述1
在端装置执行默认动作,这是打印线。
To do this "in-place" on a file, you have to jump through a few hoops:
要在文件上“就地”执行此操作,您必须跳过几个环节:
$ perl -i -pe 's/\d+$/$&+($&>0)/e if /foo/' knownfile.txt
Newer versions of gawk
support in-place editing but this will work everywhere.
较新版本的gawk
支持就地编辑,但这将适用于任何地方。
回答by bobbogo
use Fcntl;
my $fh;
open $fh,"+<$ARGV[0]";
while(<$fh>) {
if (/foo/) {
s/(-?\d+)/(( > 0) ? (+1) : )/ge;
}
$file .= $_;
}
seek($fh, 0, SEEK_SET);
print $fh $file;
close $fh;
Doesn't see -32
as negative.
不认为-32
是负面的。
回答by Astrinus
This script has no downsides.
这个脚本没有缺点。
##代码##