Issue
I try to replace/append strings in text files with sed
.
Another string ("green") needs to be matched before a replacement is allowed.
apple >> apple_tree
apple X1 >> apple_tree
appleX1 >> apple_tree
This code works if the condition is not taken into account and the first occurrence of one of the strings should be replaced:
find . -type f -exec sed -i '0,/apple|apple X1|appleX1/{s/apple|apple X1|appleX1/apple_tree/}' {} +
This code can not be executed (prompt is waiting)
find . -type f -exec sed -i '/green/,// /apple|apple A0|appleA0/{s/apple|apple A0|appleA0/apple_tree/}' {} +
Although this one works without alternative patterns:
find . -type f -exec sed -i '/green/,// s/apple/apple_tree/' {} +
Unfortunately, using word border indicators like \<apple\> does not work either.
The OS is Ubuntu 20.04. The solution is not restricted to sed
.
Thank you.
Edit:
Input:
orange
pear
kiwi
apple X1
mango
banana
apple
green
orange
pear
kiwi
apple X1
mango
appleX1
banana
apple
Code execution
Desired output:
orange
pear
kiwi
apple X1
mango
banana
apple
green
orange
pear
kiwi
apple_tree
mango
apple_tree
banana
apple_tree
Solution
You seem to want:
sed -i -e '/green/,$s/apple\( A0\|A0\|\)/apple_tree/'
Check out https://www.gnu.org/software/sed/manual/sed.html https://www.grymoire.com/Unix/Sed.html https://regexcrossword.com/
Answered By - KamilCuk Answer Checked By - Terry (WPSolving Volunteer)