Srikishan
Srikishan

Reputation: 1

How to replace a paragraph with new paragraph

I have a file which has alot of PIN. The situation is as shown below

PIN ABC
DIRECTION INPUT
USE SIGNAL

I want to replace this with

PIN ABC
DIRECTION INPUT
USE POWER

such that the signal is changed to power only when PIN ABC is appears in the file. Is it possible to do it with grep or awk.

Upvotes: 0

Views: 503

Answers (4)

Ed Morton
Ed Morton

Reputation: 203975

Using awk, rewrite lines starting with USE after a line with PIN ABC. The final 1 prints the (possibly modified) line.

$ awk '/^PIN/{pin=$2} /^USE/&&(pin=="ABC"){$2="POWER"} 1' file
PIN ABC
DIRECTION INPUT
USE POWER

Upvotes: 1

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed -n '1h;1!H;${x;/PIN ABC/ s/USE SIGNAL/USE POWER/g;p;}' YourFile
  • dont print line unless requested
  • load the file in buffer (1st line overwritte, other append)
  • at the end
    • if PIN ABC is found, change USE SIGNAL
    • print result

Now, you certainly mean lot of different PIN ABC (not clear between several same ABC or several PIN with different ABC), in this case this script, like this does not suite because it change EVERY USE SIGNAL at first occurence

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 247002

Assuming your "paragraphs" are separated by blank lines:

perl -00 -pe 's/^(PIN ABC.*USE) \w+/$1 POWER/s' <<END
some stuff

PIN ABC
DIRECTION INPUT
USE SIGNAL

PIN DEF
USE SIGNAL

more stuff
END
some stuff

PIN ABC
DIRECTION INPUT
USE POWER

PIN DEF
USE SIGNAL

more stuff

This uses

  • option -00 to read paragraphs, not lines
  • -p to loop over the records and implicitly print after modifications
  • the s modifier to the s/// command to allow . to match newlines

Upvotes: 2

Jotne
Jotne

Reputation: 41460

You can use this awk

awk '/^PIN ABC/ {a=NR} a+2==NR {$2="POWER"} 1' file
PIN ABC
DIRECTION INPUT
USE POWER

If number of lines between PIN and USE is not fixed:

awk '/^PIN/ {f=1} f && /^USE/ {$2="POWER";f=0} 1' file
PIN ABC
DIRECTION INPUT
USE POWER

Upvotes: 2

Related Questions