如何用多行搜索和替换多行 [英] How to search and replace multiple lines with multiple lines
问题描述
我查看了有关搜索和替换的其他答案,但我只是不理解模式.
I looked at other answers regarding search and replace, but I just can't understand the patterns.
如何更改文件的这一部分(行号153 ... 156)
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
}
推荐答案
这可能对您有用(GNU sed& Bash):
This might work for you (GNU sed & Bash):
sed $'153r replacementFile\n;153,156d' file
或对于大多数sed:
sed -e '153r replacementFile' -e '153,156d' file
或者,如果您愿意:
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
前一个\
保留前导空间,其后的每一行除外,最后一行需要附加\
.当空行由单个\
表示时,SO中的markdown格式不正确(因此,我删除了替换行的第二行),但是大多数shell应该如此.
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.
这篇关于如何用多行搜索和替换多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!