Dev
Dev

Reputation: 55

Command to replace data in the nth column if the line begins with pattern

I have a file which looks like below:

16815966|Mr|Fit 5|Dont Usee|15-07-2015|||||||||||||0|2|0|0.00|0|  
21875307|Mr|Father|Dont Remove|X|31-12-1899|||||||||||||0|118|0|0.00|0|
19180802|Mr|Dontye|Harr|01-01-1900|||||6666|Avenue||||||06-09-2013|0|26|2|396.00|1|   

I Want to replace 4th column value with blank if begins with "Dont" and pattern like Dont Remove, Dont Use. But if its like one in 3rd example i wanna retain it.

Desired Result:

16815966|Mr|Fit 5||15-07-2015|||||||||||||0|2|0|0.00|0|  
21875307|Mr|Father||X|31-12-1899|||||||||||||0|118|0|0.00|0|
19180802|Mr|Dontye|Harr|01-01-1900|||||6666|Avenue||||||06-09-2013|0|26|2|396.00|1|    

Tried below and one with awk but no luck!! sed '/^Dont/s/[^|]*//4'.

Upvotes: 2

Views: 233

Answers (2)

Srdjan M.
Srdjan M.

Reputation: 3405

Solution for PHP.

Regex: (?m)^(?:[\w ]+\|){3}\K(?:(Dont))(?(1)[^\|]+) Substitution: "" empty string.

$text = '16815966|Mr|Fit 5|Dont Usee|15-07-2015|||||||||||||0|2|0|0.00|0|  
         21875307|Mr|Father|Dont Remove|X|31-12-1899|||||||||||||0|118|0|0.00|0|
         19180802|Mr|Dontye|Harr|01-01-1900|||||6666|Avenue||||||06-09-2013|0|26|2|396.00|1|';

$text = preg_replace('/(?m)^(?:[\w ]+\|){3}\K(?:(Dont))(?(1)[^\|]+)/', "",$text);
print_r($text);

Output:

16815966|Mr|Fit 5||15-07-2015|||||||||||||0|2|0|0.00|0|  
21875307|Mr|Father||X|31-12-1899|||||||||||||0|118|0|0.00|0|
19180802|Mr|Dontye|Harr|01-01-1900|||||6666|Avenue||||||06-09-2013|0|26|2|396.00|1|

Regex demo

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133458

Following awk may help you in same.

awk -F"|" '$4~/^Dont/{$4=""} 1' OFS="|"  Input_file

Output will be as follows.

16815966|Mr|Fit 5||15-07-2015|||||||||||||0|2|0|0.00|0|
21875307|Mr|Father||X|31-12-1899|||||||||||||0|118|0|0.00|0|

Upvotes: 3

Related Questions