Sed with multiple lines does not replace pattern
I have been massaging with sed (found tutorial here: Grymoire ) ASCII files we get from our hardware suppliers. Files have a structure like so
Model-Manufacturer:D12-500
Test_Version:2.6.3
But some files we receive are randomly "broken" and miss an entry for "Model-Manufacturer:"
Model-Manufacturer:D12-500
Test_Version:2.6.3
Model-Manufacturer:H24-700
Test_Version:2.6.3
Test_Version:2.6.3
Model-Manufacturer:R15-300
Test_Version:2.6.3
I want to fix this problem with Sed and place the missing entry for "Model-Manufacturer:N/A" before the second occurence of "Test_Version:2.6.3" ; this is my code
sed -n '
/Test_Version/ {
# found "Test_Version" - r开发者_如何学Pythonead in next line
N
# look for "Test_Version" on the second line
# and print if there.
/\n.*Test_Version/ {
# found it - now edit making one line
s/Test_Version/Model-Manufacturer:N/A/
}
}' infile > outfile
It's not working. I believe I need to remember the position of each "Test_Version" and "Model_Manufacturer" before doing the replacement, correct? Can I do this with sed?
Thanks in advance for your input.
Change your substitution to:
s||\nModel-Manufacturer:N/A&|
Using an alternate delimiter means you don't have to escape the slash in "N/A". Using an empty left side reuses the most recent match. The ampersand copies the match into the right side.
Also, you need to remove the -n
.
If I understand what you are trying to achieve, you are very close. I think changing the substitution command to the following makes it work:
s/\nTest_Version/\nMode-Manufacturer:N\/A\nTest_Version/
精彩评论