Bash 如何搜索和替换多行文字AWK
我有一个包含以下内容的文件(代码片段)——测试可以在文件中的任何位置Bash 如何搜索和替换多行文字AWK,bash,awk,sed,Bash,Awk,Sed,我有一个包含以下内容的文件(代码片段)——测试可以在文件中的任何位置 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 我想替换:(包括缩进) 与 关于使用awk/sed实现这一目标有何建议?谢谢
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
我想替换:(包括缩进)
与
关于使用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:
块已被替换
$ 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