Reputation: 704
I want to modify a line that exists between 2 lines in a paragraph. For example I have this file that contains
fruits
apple
banana
end fruits
----
all list
egg
milk
banana
end list
I want to change the banana inside the fruits block (between fruits and end fruits) to berry. How to do so?
Upvotes: 0
Views: 71
Reputation: 4453
This may suit your needs:
awk '
fruits && /banana/ { $0 = "berry" }
/fruits/ { fruits = 1 }
/end fruits/ { fruits = 0 }
1
'
The above code has a BIG assumption: that it's ok to change the entire line if "banana" appears in between "fruits" and "end fruits". If you just want to replace the "bananas", you can change the action as follows:
awk '
fruits && /banana/ { gsub( "banana", "berry" ) }
/fruits/ { fruits = 1 }
/end fruits/ { fruits = 0 }
1
'
Above we are replacing all "banana" with "berry", as opposed to replacing the whole line ( $0 ). And now since we are using gsub(), we can actually remove the "&& /banana/" to yield this:
awk '
fruits { gsub( "banana", "berry" ) } # if in fruits, do sub
/fruits/ { fruits = 1 } # weve entered the fruits block
/end fruits/ { fruits = 0 } # weve left the block
1 # print each line
'
luciole suggests using ranges. Here's the program one more time using ranges (and eliminating the fruits flag):
awk '
/fruits/,/end fruits/ { gsub( "banana", "berry" ) }
1
'
Using a range above, the program looks A LOT like Cyrus' answer.
Upvotes: 3
Reputation: 88979
With sed:
sed '/^fruits$/,/^end fruits$/{ s/banana/berry/ }' file
Output:
fruits apple berry end fruits ---- all list egg milk banana end list
Upvotes: 5
Reputation: 133770
Could you please try following.
awk '
/^fruits$/{
found=1
}
found && /banana/{
$0="your new line here"
found=""
}
1
' Input_file
Explanation: Adding detailed explanation for above code.
awk ' ##Starting awk program from here.
/^fruits$/{ ##Checking if a line has value fruits in it then do following.
found=1 ##Setting value of found to 1 here, kind of FLAG to check either fruits string found in lines till now or not.
}
found && /banana/{ ##Checking condition if string banana found in line and variable found is SET then do following.
$0="your new line here" ##Setting current line value to new line value here.
found="" ##Nullifying variable found here.
}
1 ##Mentioning 1 will print edited/non-edited lines here.
' Input_file ##Mentioning Input_file name here.
Upvotes: 3