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

sed regex to match exact pattern and ignore some pattern

I have a YML, in which I need to append numeric with double quotes. I tried various regex but somehow it gets break somewhere or other. I need to avoid alphanum or alpha…

- name: HEALTH_ELASTIC_HOST 
  value: 40c07d4283d245.elastic.test.com
- name: HEALTH_ELASTIC_PORT
  value: 9243
- name: HEALTH_ELASTIC_USERNAME
  value: elastic

The basic cmd which I took, and modified

sed 's/[0-9]*[0-9]/"&"/g' values.yaml

Expected Result

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

- name: HEALTH_ELASTIC_HOST 
  value: 40c07d4283d245.elastic.test.com
- name: HEALTH_ELASTIC_PORT
  value: "9243"
- name: HEALTH_ELASTIC_USERNAME
  value: elastic

Any help is appreciated..link to any doc or cmd.

>Solution :

You may use this sed:

sed -E 's/([: ]+)([0-9]+) *$/\1"\2"/' file.yml

- name: HEALTH_ELASTIC_HOST
  value: 40c07d4283d245.elastic.test.com
- name: HEALTH_ELASTIC_PORT
  value: "9243"
- name: HEALTH_ELASTIC_USERNAME
  value: elastic

Explanation:

  • ([: ]+): Match 1+ of : or space and capture in group #2
  • ([0-9]+): Match 1+ digits an capture in group #2
  • *: Match 0 or more spaces
  • $: match end position
  • \1"\2": In substitution we wrap back-reference #2 with double quotes
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