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
- 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.
CodePudding user response:
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
CodePudding user response:
With your shown samples please try following(experts advise to use yq like tools to edit yaml since OP is using sed here so going with it).
sed -E 's/(^[[:space:]] value: )([0-9] $)/\1"\2"/g' Input_file
Explanation: Simple explanation would be, Using sed's -E option to enable ERE(extended regular expressions) then in main program using regex (^[[:space:]] value: )([0-9] $) along with substitute option of sed. Regex((^[[:space:]] value: )([0-9] $)) will create 2 capturing groups, where 1st one will have values like: value: in it and 2nd capturing group will have digits in it.
Then while performing substitution simply substituting it with 1st capturing group followed by " and 2nd capturing group followed by " as per requirement.
CodePudding user response:
Using sed
$ sed 's/\<[0-9]\ \>/"&"/' input_file
- name: HEALTH_ELASTIC_HOST
value: 40c07d4283d245.elastic.test.com
- name: HEALTH_ELASTIC_PORT
value: "9243"
- name: HEALTH_ELASTIC_USERNAME
value: elastic
