Wednesday, October 27, 2021

[SOLVED] Delete records if no data exists after colon using sed

Issue

I have data in below format in a file

id : 315,abcid                 :,abcname                 :,abcrole                :,abctest                :,abcsts : Active,abcqwe                :
id : 316,abcid :1234 ,abcname : Test,abcrole : No,abctest : 2345,abcsts : Active,abcqwe                :

I am trying to get all fields which has data after : in the below format :--

id : 315,abcsts : Active ,
id : 316,abcid :1234 ,abcname : Test,abcrole : No,abctest : 2345,abcsts : Active,

I tried using sed to but it deleting whole records.

Any help is appreciated.

Regards


Solution

Perl to the rescue!

perl -pe 's/(,|^)\S+\s*:(?=,|$)//g' file

The (?=...) is a look-ahead assertion, i.e. it checks that the following character is a comma or end of line, but doesn't remove it and doesn't advance the position for the next search.

The output is different to the one you specified: it also removes the final commas.



Answered By - choroba