Seda is replaced on second appearance

I want to remove the template with sed, only on the second appearance. Here is what I want to remove the template, but in the second case.

What is in the .csv file:

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 

Required Conclusion:

 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 

This is what I tried:

 sed -r 's/(\(null)\).*csv//' file.csv 

The problem here is that the regex is too greedy, but I can't do it, stop it. I also tried this to skip the first occurrence of "null":

 sed -r '0,/null/! s/(\(null)\).*csv//' file.csv 

Also tried, but greedy regex is still a problem.

 sed -r 's/(\(null)\).*csv//2' file.csv 

I read that ? can make the regular expression β€œlazy,” but I can't make it a workout.

 sed -r 's/(\(null)\).*?csv//' file.csv 
+5
source share
3 answers

More robust awk solution:

File with extended examples 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 

Task:

 awk -F, '{ c=0; for(i=1;i<=NF;i++) if($i~/\(null\)/ && c++==1) sub(/\(null\).*/,"",$i) }1' OFS=',' input.csv 

Output:

 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 
+1
source

sed provides an easy way to indicate which match should be replaced. Just add the number after the delimiters

 $ sed 's/(null)[^.]*\.csv//2' ip.csv 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 $ # or [^,] if there are no , within fields $ sed 's/(null)[^,]*//2' ip.csv 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 

Also, no need to run () unless using extended regular expressions

+4
source

Execute:

 awk '{sub(/.null.....csv,f/,",f")}1' file 

And the output should be:

 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 
-1
source

Source: https://habr.com/ru/post/1271838/


All Articles