简体   繁体   中英

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

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.

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, eg:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM