sp2
sp2

Reputation: 599

How to replace one or more consecutive symbols with one symbol in shell

I have a file containing consecutive symbols (as pipe "|") like

ANKRD54,LIAR,allergy,|||
ANKRD54,LIAR,asthma,||20447076||
ANKRD54,LIAR,autism,||||
ANKRD54,LIAR,cancer,|||
ANKRD54,LIAR,chronic_obstructive_pulmonary_disease,|||
ANKRD54,LIAR,dental_caries,||||

Now using shell or a sed command in shell is it possible to replace multiple pipe with one pipe like

    ANKRD54,LIAR,allergy,|
    ANKRD54,LIAR,asthma,|20447076|
    ANKRD54,LIAR,autism,|
    ANKRD54,LIAR,cancer,|
    ANKRD54,LIAR,chronic_obstructive_pulmonary_disease,|
    ANKRD54,LIAR,dental_caries,|

Upvotes: 0

Views: 105

Answers (3)

Inian
Inian

Reputation: 85580

You can do that with a simple awk gsub as:-

awk -F"," -v OFS="," '{gsub(/[|]+/,"|",$4)}1' file

See it in action:-

$ cat file
ANKRD54,LIAR,allergy,|||
ANKRD54,LIAR,asthma,||20447076||
ANKRD54,LIAR,autism,||||
ANKRD54,LIAR,cancer,|||
ANKRD54,LIAR,chronic_obstructive_pulmonary_disease,|||
ANKRD54,LIAR,dental_caries,||||

$ awk -F"," -v OFS="," '{gsub(/[|]+/,"|",$4)}1' file
NKRD54,LIAR,allergy,|
ANKRD54,LIAR,asthma,|20447076|
ANKRD54,LIAR,autism,|
ANKRD54,LIAR,cancer,|
ANKRD54,LIAR,chronic_obstructive_pulmonary_disease,|
ANKRD54,LIAR,dental_caries,|

Upvotes: 1

d4l
d4l

Reputation: 66

I guess the easiest way is use built-in commands: cat your_file | tr -s '|'

Upvotes: 2

Fernando Miguélez
Fernando Miguélez

Reputation: 11316

Pass your text to sed (e.g. via a pipe)

cat your_file | sed "s/|\+/|/g"

Upvotes: 2

Related Questions