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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With