Problem editting the first occurence of a pattern in the first uncommented line

Hi

I have to replace a pattern found in the first uncommented line in a file. The challenge I'm facing is there are several such similar lines but I have to edit only the first uncommented line.

Eg:

#this is example
#/root/xyz:Old_Pattern
/root/xyz:Old_Pattern
/root/xyz:Old_Pattern

Want to change it to

#this is example
#/root/xyz:Old_Pattern
/root/xyz:Changed_Pattern
/root/xyz:Old_Pattern

The only delimiter i can use is ":"

The present code im using is
`sed -ie '1,/^#.*.:.*/!s/:.*/:Changed_Pattern/1' /root/tmp.file`

however it is editing all the similar uncommented lines

Eg; happening
#this is example
#/root/xyz:Old_Pattern
/root/xyz:Changed_Pattern
/root/xyz:Changed_Pattern

Pls can someone help
Thank You

Pls use code tags as advised.
Try

$ awk -F: '!/^#/ && !Done{sub("Old_Pattern","Changed_Pattern",$2);Done++}1' OFS=":" file
#this is example
#/root/xyz:Old_Pattern
/root/xyz:Changed_Pattern
/root/xyz:Old_Pattern

You can use sed's q option to quit reading further lines. So try

$ sed -ie '/^#/!{
> s/:.*/:Changed_Pattern/
> q
> }' inputfile

Wouldn't this lose any further lines?

I believe it would not. Could you test it? My machine does not support -i option.

Hi RudiC

It works and thanks for your time but I have problem there as I cant give the pattern "Old_Pattern" as that can be anything and I used "*" which didnt work. Im really new to awk so can you help me

---------- Post updated at 03:48 AM ---------- Previous update was at 03:38 AM ----------

Hi michaelrozar17

The code that you have posted deletes all the further lines

So you want to set field 2 of first non-comment line to "Changed_Pattern" regardless of its previous value? Try

$ awk -F: '!/^#/ && !Done{$2="Changed_Pattern");Done++}1' OFS=":" file 

Hmmm Im getting a syntax error

awk: cmd. line:1: !/^#/ && !Done{$2="Changed_Pattern");Done++}1
awk: cmd. line:1: ^ syntax error

---------- Post updated at 04:01 AM ---------- Previous update was at 03:57 AM ----------

Hmmm Im getting a syntax error

awk: cmd. line:1: !/^#/ && !Done{$2="Changed_Pattern");Done++}1
awk: cmd. line:1: ^ syntax error

---------- Post updated at 04:02 AM ---------- Previous update was at 04:01 AM ----------

Im getting a error message

awk: cmd. line:1: !/^#/ && !Done{$2="Changed_Pattern");Done++}1
awk: cmd. line:1: ^ syntax error

Try removing this round bracket..highlighted in Red..

awk -F: '!/^#/ && !Done{$2="Changed_Pattern");Done++}1' OFS=":" file

Corrected one..

awk -F: '!/^#/ && !Done{$2="Changed_Pattern";Done++}1' OFS=":" file

Rats - overlooked that right parenthesis when adapting earlier proposal. Yes, just remove it.

Thanks all

Yes i tried correcting the syntax and it worked wonderfully. Thanks all once again. esplly rudiC :slight_smile: