bash - 如何搜索和替换多行文本AWK
问题描述
我有一个包含以下内容的文件(片段)——测试可以在文件中的任何位置。
More text here
Things-I-DO-NOT-NEED:
name: "Orange"
count: 8
count: 10
Things-I-WANT:
name: "Apple"
count: 3
count: 4
More text here
我想替换:(包括缩进)
Things-I-WANT:
name: "Apple"
count: 3
count: 4
和
Things-I-WANT:
name: "Banana"
count: 7
关于使用 awk/sed 实现它的任何建议?谢谢!
解决方案
你可以这样做awk
:
#!/usr/bin/env awk
# Helper variable
{DEFAULT = 1}
# Matches a line that begins with an alphabet
/^[[:alpha:]]+/ {
# This matches "Things-I-WANT:"
if ($0 == "Things-I-WANT:") {
flag = 1
}
# Matches a line that begins with an alphabet and which is
# right after "Things-I-WANT:" block
else if (flag == 1) {
print "\tname: \"Banana\""
print ""
print "\tcount: 7"
print ""
flag = 0
}
# Matches any other line that begins with an alphabet
else {
flag = 0
}
print $0
DEFAULT = 0
}
# If line does not begin with an alphabet, do this
DEFAULT {
# Print any line that's not within "Things-I-WANT:" block
if (flag == 0) {
print $0
}
}
您可以bash
使用以下命令运行它:
$ awk -f test.awk test.txt
该脚本的输出将是:
More text here
Things-I-DO-NOT-NEED:
name: "Orange"
count: 8
count: 10
Things-I-WANT:
name: "Banana"
count: 7
More text here
如您所见,该Things-I-WANT:
块已被替换。
推荐阅读
- c - 声明/初始化结构时,每个花括号代表什么?(警告:初始化器 [-Wmissing-braces] 周围缺少大括号)
- c# - 如何删除类别和子类别?
- javascript - 是否可以从 JavaScript 更新 python 中的变量?
- angular - 使用数据布尔值展开/折叠材质树(Angular 7)
- apache-spark - 在 pyspark 中的 DataFrame 上使用 toPandas() 时出现神秘的“pyarrow.lib.ArrowInvalid:浮点值被截断”错误
- javascript - 从 RiotJS 中的异步更新事件刷新模板
- javascript - Google gtag_report_conversion:如何在不重新加载页面的情况下使用它?
- ember.js - Rails API - 如何启用 ActiveStorage::DirectUploadsController
- javascript - 谷歌标签管理器最接近文本
- python - TypeError:“float32”类型的对象不是 JSON 可序列化的