Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed to replace specific string, in multiple lines which are between some pattern

Tags:

bash

sed

I have a simple question (I think), I need to replace a specific string which occurs in multiple lines in a file (verilog). These lines are themselves between specific patterns

ex:

lk
lk
lk
lk
lk

//comment1
input [5:0]a,
input [3:0]b,
input c,
input [4:0]d,
input f,

//comment2
lm
lm
lm
lm

I need to replace "input" with "logic" between "comment1" and "comment2" keeping them as it is in the final result (quotes not included, only for understanding)

Right now what I have is

sed '/\/comment1/,/\/comment2/s/input/logic/g' file1.sv > file2.sv

the result I get is

lk
lk
lk
lk
lk

//comment1
logic
logic
logic
logic
logic

//comment2
lm
lm
lm
lm

The rest of the text after logic is gone, I need to preserve that

Can someone please help, I will be grateful...

like image 737
user3158281 Avatar asked Mar 12 '26 12:03

user3158281


1 Answers

You can use this sed command:

sed -i.bak '/\/\/comment1/,/\/\/comment2/s/\<input\>/logic/g' file
  • /\/\/comment1/,/\/\/comment2/ is to search text between 2 comment blocks
  • \<input\> is for matching input with word boundaries
  • s/\<input\>/logic/g is for replacing "input" with "logic"
like image 62
anubhava Avatar answered Mar 15 '26 07:03

anubhava



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!