I would like to search for a pattern in bunch of source files. The pattern should act as a marker. If the pattern is found, I would like to process that line by performing a substitution of another string
For example:
Private const String myTestString = @"VAL15"; // STRING—REPLACE-VAL##
Here, I want to search my source file for pattern STRING—REPLACE-VAL
and then replace VAL15
with VAL20
in same.
Output:
private const String myTestString = @"VAL20"; // STRING—REPLACE-VAL##
Tried below command but not working as expected.
sed -i '/,STRING—REPLACE-VAL##/ {; s/,VAL15,/,VAL20,/;}' myTestFile.cpp
Question: Is it possible to search for STRING—REPLACE-VAL##
and then search for matching pattern @"VAL
??" in same line and replace 15 by 20.
sed
supports search & replacing the same pattern very easily but not sure if sed
supports to search pattern but replace another string in the matching line?
Any help would be appreciated. Thanks in advance.
`sed` command is one of the ways to do replacement task. This command can be used to replace text in a string or a file by using a different pattern.
You were very close :
sed -i '/STRING—REPLACE-VAL##/{s/VAL15/VAL20/}' myTestFile.cpp
In your original you were trying to replace ",VAL15,"
but this string is not in the line (the commas). Furthermore, the same occurs for your search string ",STRING—REPLACE-VAL##"
.
It also occured to me that the first hyphen between STRING
and REPLACE
is an em-dash and not a standard -
, maybe this is another problem. Make sure that the string is exactly the same. If you are not sure about the dashes, you could use
sed -i '/STRING.REPLACE.VAL##/{s/VAL15/VAL20/}' myTestFile.cpp
and to answer your question, yes you can try to do multiple matches in the following way:
sed
:
sed -i '/STRING.REPLACE.VAL##/{ /@"VAL/ { s/VAL15/VAL20/ } }' myTestFile.cpp
awk
:
awk '/STRING.REPLACE.VAL##/&&/@"VAL/{sub("VAL15","VAL20")}1' myTestFile.cpp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With