Friday, January 26, 2024

[SOLVED] is there a better dynamic way to replace if any digit except 0 exists using sed/awk

Issue

Team, my output is below and I want to replace all non-zeros after comma to boolean 1.

DA:74,0
DA:75,0
DA:79,3 < NON BOOLEAN
DA:80,3 < NON BOOLEAN
DA:81,3 < NON BOOLEAN
DA:82,4 < NON BOOLEAN
DA:83,1

so I did this sed 's/,[1-999]/,1/g'

but I can't be increasing 999 to 9999 kind of manual. is there a dynamic way that if no 0 then replace with one. 1

expected output

DA:74,0
DA:75,0
DA:79,1
DA:80,1
DA:81,1
DA:82,1
DA:83,1

possible values are any combinations like

DA:108,23
DA:110,101
DA:111,098
DA:112,100

all above should be replaced by 1. so only case it should replace is when there is single digit 0 or single digit 1.

so any non-zero number with a comma before should be replaced.


Solution

You can use this command:

sed -E 's/,([1-9]|[0-9]{2,})$/,1/'

It will find all lines ending with (comma, single digit != 0) or (comma, multiple digits) and replace them with ,1

Demo here.



Answered By - markalex
Answer Checked By - Mary Flores (WPSolving Volunteer)