Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search and replace multiple lines with multiple lines

Tags:

grep

bash

sed

awk

perl

I looked at other answers regarding search and replace, but I just can't understand the patterns.

How can I change this part of a file (line numbers 153 ... 156)

        let view = string.utf8
        offset.pointee += string.substring(to: range.lowerBound).utf8.count
        length.pointee = Int32(view.distance(from:range.lowerBound.samePosition(in: view), to:range.upperBound.samePosition(in: view)))
        return token

and replace it with the lines below?

        let view:String.UTF8View = string.utf8

        if let from = range.lowerBound.samePosition(in: view),
           let to = range.upperBound.samePosition(in: view) {
            offset.pointee += Int32(string[string.startIndex..<range.lowerBound].utf8.count)
            length.pointee = Int32(view.distance(from: from, to: to))
            return token
        } else {
            return nil
        }
like image 1000
sirvon Avatar asked Dec 02 '17 20:12

sirvon


1 Answers

This might work for you (GNU sed & Bash):

sed $'153r replacementFile\n;153,156d' file

or for most seds:

sed -e '153r replacementFile' -e '153,156d' file

or if you prefer:

sed '153,156c\        let view:String.UTF8View = string.utf8\
    if let from = range.lowerBound.samePosition(in: view),\
       let to = range.upperBound.samePosition(in: view) {\
        offset.pointee += Int32(string[string.startIndex..<range.lowerBound].utf8.count)\
        length.pointee = Int32(view.distance(from: from, to: to))\
        return token\
    } else {\
        return nil\
    }' file

N.B. The first \ preserves leading space and each line following except the last needs to be appended with \. The markdown in SO does not format properly when an empty line is represented by a single \ (so I removed the second line of the replacement) but most shells should.

like image 110
potong Avatar answered Sep 24 '22 05:09

potong