Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed replace with regex

Tags:

regex

file-io

sed

I can't get a simple regex replacement to work with sed. Here is the example I'm faced with.

I am trying to replace lines in a file, from this:

select * from mytable where mytable.s_id=274
select * from mytable where mytable.s_id=275
select * from mytable where mytable.s_id=276
select * from othertable where othertable.id=?
select * from table3 where table3.name=?

to this:

select * from mytable where mytable.s_id=?
select * from mytable where mytable.s_id=?
select * from mytable where mytable.s_id=?
select * from othertable where othertable.id=?
select * from table3 where table3.name=?

I am using sed as such for now:

cat log | sed 's/where mytable\.s_id=[0-9]+/where mytable.s_id=/g' | sort

But the regex I am using in sed ('s/where mytable\.s_id=[0-9]+/where mytable.s_id=/g') doesn't replace anything.

I am reading as much documentation as I can, but everything I read is different, with different way of doing things so I am a little lost. What is the canonical way for a regex replacement using sed, and what would it look like in my particuliar case?

Note: I simplified the problem I'm facing. I do want to use sed (to finally learn to use it) and I do want to pipe the input and output (not editing the file in place) because the command line I use is actually more complicated than that.

like image 519
Matthieu Napoli Avatar asked Mar 10 '26 02:03

Matthieu Napoli


1 Answers

cat log | sed 's/where mytable\.s_id=[0-9]\+/where mytable.s_id=?/g'

Just a backslash before the +.

like image 64
Tim Tosi Avatar answered Mar 11 '26 18:03

Tim Tosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!