Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace consecutive symbols using only one sed command?

I have a simple .csv file with lines that holds ‘t’ values. Here is the example:

2ABC;t;t;t;tortuga;fault;t;t;bored

I want to replace them to ‘1’ using sed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If I make sed "s/;t;/;1;/g" I get the next result:

2ABC;1;t;1;tortuga;fault;1;t;bored

As you can see, consecutive ‘;t;’ have been replaced through one. Yes, I can replace all ‘;t;’ by sed -e "s/;t;/;1;/g" -e "s/;t;/;1;/g" but this is boring.

How can I make the replacement by one sed command?

>Solution :

If there is something to replace, branch to replace again.

sed ': again; /;t;/{ s//;1;/; b again }'

Overall, parsing cvs with sed is crude. Consider awk.

awk -F';' -v OFS=';' '{ for(i=1;i<=NF;++i) $i=$i=="t"?1:$i } 1'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading