Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search a pattern in file and replace another pattern in the same line

Tags:

bash

shell

sed

awk

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.

like image 596
SwiftyCocoa Avatar asked Mar 22 '18 15:03

SwiftyCocoa


People also ask

How do you replace some text pattern with another text pattern in a file?

`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.


1 Answers

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
like image 93
kvantour Avatar answered Sep 22 '22 04:09

kvantour