Narender Bansal
Narender Bansal

Reputation: 47

how to replace multiple text line with new text

I have:

SIESTA_ARCH = unknown
CC = gcc
FPP = $(FC) -E -P -x c 
FC = gfortran 

and I want to replace this by

SIESTA_ARCH = amd64 (x86_64) 
CC = mpicc 
FPP = $(FC) -E -P -x c 
FC = mpif90

Upvotes: 0

Views: 100

Answers (3)

Pierre François
Pierre François

Reputation: 6073

I guess next solution is working for you (edited solution according to answers of the PO):

script.sed

#!/bin/sed -f

/^SIESTA_ARCH = unknown/,/^FC =/{
  s/^SIESTA_ARCH =.*/SIESTA_ARCH = amd64 (x86_64)/
  s/^CC =.*/CC = mpicc/
  s/^FC =.*/FC = mpif90/
}

Invoke as ./script.sed Makefile to see the results on the standard output or as ./script.sed -i Makefile to update the file Makefile.

This solution will change all the occurences of SIESTA_ARCH = unknown and the next line block until a line beginning with FC = into the new values.

Upvotes: 1

Jetchisel
Jetchisel

Reputation: 7831

If you have ed

cat script.ed
H
g/^\(SIESTA_ARCH =\)\(.\+\)$/s//\1 amd64 (x86_64)/
g/^\(CC =\)\(.\+\)$/s//\1 mpicc/
,p
Q

Using the script against your file.

ed -s Makefile < script.ed

Output

SIESTA_ARCH = amd64 (x86_64)
CC = mpicc
FPP = $(FC) -E -P -x c
FC = gfortran

Now change ,p Q to w and q To edit the file in-place.

H
g/^\(SIESTA_ARCH =\)\(.\+\)$/s//\1 amd64 (x86_64)/
g/^\(CC =\)\(.\+\)$/s//\1 mpicc/
w
q
ed -s Makefile < script.ed

Upvotes: 0

pallgeuer
pallgeuer

Reputation: 1376

In bash you can define a function like this (just execute this one-liner in a terminal or script):

function repl() { FIND="$2" REPLACE="$3" ruby -p -i -e "gsub(ENV['FIND'], ENV['REPLACE'])" "$1"; }

Then you can replace whatever literal strings you want in whatever file, e.g.:

repl ~/Code/Makefile 'SIESTA_ARCH = unknown' 'SIESTA_ARCH = amd64 (x86_64)'
repl ~/Code/Makefile 'CC = gcc' 'CC = mpicc'
repl ~/Code/Makefile 'FC = gfortran' 'FC = mpif90'

Note that this will replace all occurrences of such strings in the specified file.

Upvotes: 0

Related Questions