我查看了有关搜索和替换的其他答案,但我就是无法理解其中的模式。
如何更改文件的这一部分(行号 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
并将其替换为下面的行?
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):
sed $'153r replacementFile\n;153,156d' file
或者对于大多数 seds:
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 应该。
关于bash - 如何用多行搜索和替换多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47612102/