[英]sed replace number with number-1
Can sed handle a substitution and simultaneously evaluate an expression to substitute somehow? sed可以处理替换并同时评估表达式以某种方式替换吗?
For example, I have the following entry in a text file: 例如,我在文本文件中具有以下条目:
##################################### topd Tree1 - Tree14 #######################################
For reasons I won't go in to, each Tree's number is N+1 relative to another numbering scheme I've been using so far. 由于我不愿讨论的原因,相对于我到目前为止使用的另一种编号方案,每棵树的编号为N + 1。
Could sed (or any util really, sed is just my go to for find-and-replace operations), find every instance of TreeN
and replace them with TreeN-1
such that the above line would then look like: 可以sed(或者真的是任何util,sed只是我去查找和替换操作所需要的),找到每个TreeN
实例并将它们替换为TreeN-1
,使得上一行如下所示:
##################################### topd Tree0 - Tree13 #######################################
(Using Ubuntu 12.02, so pretty much anything goes.) (使用Ubuntu 12.02,几乎可以完成所有工作。)
Using perl 使用Perl
perl -pe 's/Tree\K\d+/$&-1/ge' file
Output 产量
##################################### topd Tree0 - Tree13 #######################################
I'd use perl in this case, with the e
modifier to evaluate an expression in the replacement part: 在这种情况下,我将使用perl以及e
修饰符来评估替换部分中的表达式:
perl -pe 's/(Tree)(\d+)/$1 . ($2 - 1)/ge'
You can also take advantage of more advanced regular expression support, eg by using a lookbehind assertion: 您还可以利用更高级的正则表达式支持,例如通过使用后置断言:
perl -pe 's/(?<=Tree)(\d+)/$1 - 1/ge'
You can try this; 您可以尝试一下;
sed 's/[^0-9,-]*//g' filename | sed -e "s/-/ /g" | awk '{print "##################################### topd Tree"$1-1 " - Tree" $2-1 " #######################################"}'
awk '{gsub(/Tree/,"Tree ",$0);print $1" "$2" "$3$4-1" "$5" "$6$7-1" "$8}' filename
Using gnu awk below 在下面使用gnu awk
awk '{
for(i=1;i<=NF;i++){
$i ~ /^Tree[[:digit:]]+$/
{
n=(gensub(/Tree/,"",1,$i)-1);
$i=gensub(/Tree([[:digit:]]+)/,"Tree"n,1,$i);
}
}
print}' file
would do the trick 会做到的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.