Reputation: 93
I have a file with following content (snippet) -- The test could be anywhere in the file.
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
I would like to replace : (Including indentation)
Things-I-WANT:
name: "Apple"
count: 3
count: 4
with
Things-I-WANT:
name: "Banana"
count: 7
Any suggestions on achieving it using awk/sed? Thanks!
Upvotes: 1
Views: 3149
Reputation: 1562
You can do this in 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
}
}
You can run this in bash
using:
$ awk -f test.awk test.txt
The output of this script will be:
More text here
Things-I-DO-NOT-NEED:
name: "Orange"
count: 8
count: 10
Things-I-WANT:
name: "Banana"
count: 7
More text here
As you can see, the Things-I-WANT:
block has been replaced.
Upvotes: 3