sed在第二次出现时替换 [英] Sed replace at second occurrence
本文介绍了sed在第二次出现时替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只想在第二次出现时用sed删除模式.这就是我想要的,删除模式但第二次出现.
I want to remove a pattern with sed, only at second occurence. Here is what I want, remove a pattern but on second occurrence.
file.csv中包含什么:
What's in the file.csv:
a,Name(null)abc.csv,c,d,Name(null)abc.csv,f
a,Name(null)acb.csv,c,d,Name(null)acb.csv,f
a,Name(null)cba.csv,c,d,Name(null)cba.csv,f
想要的输出:
a,Name(null)abc.csv,c,d,Name,f
a,Name(null)acb.csv,c,d,Name,f
a,Name(null)cba.csv,c,d,Name,f
这是我尝试过的:
sed -r 's/(\(null)\).*csv//' file.csv
这里的问题是正则表达式太贪婪了,但我不能停下来. 我也尝试过此操作,以跳过首次出现的空":
The problem here is that the regex is too greedy, but i cannot make is stop. I also tried this, to skip the first occurrence of "null":
sed -r '0,/null/! s/(\(null)\).*csv//' file.csv
也尝试过,但是贪婪的正则表达式仍然是问题所在.
Also tried but the greedy regex is still the problem.
sed -r 's/(\(null)\).*csv//2' file.csv
我已经读到?
可以使正则表达式变得懒惰",但我无法使其正常运行.
I've read that ?
can make the regex "lazy", but I cannot make it workout.
sed -r 's/(\(null)\).*?csv//' file.csv
推荐答案
更强大的 awk 解决方案:
扩展样本文件input.csv
:
12,Name(null)randomstuff.csv,2,3,Name(null)randomstuff.csv, false,Name(null)randomstuff.csv
12,Name(null)AotherRandomStuff.csv,2,3,Name(null)AotherRandomStuff.csv, false,Name(null)randomstuff.csv
12,Name(null)alphaNumRandom.csv,2,3,Name(null)alphaNumRandom.csv, false,Name(null)randomstuff.csv
工作:
The job:
awk -F, '{ c=0; for(i=1;i<=NF;i++) if($i~/\(null\)/ && c++==1) sub(/\(null\).*/,"",$i) }1' OFS=',' input.csv
输出:
12,Name(null)randomstuff.csv,2,3,Name, false,Name(null)randomstuff.csv
12,Name(null)AotherRandomStuff.csv,2,3,Name, false,Name(null)randomstuff.csv
12,Name(null)alphaNumRandom.csv,2,3,Name, false,Name(null)randomstuff.csv
这篇关于sed在第二次出现时替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文