diego-bf
diego-bf

Reputation: 11

for each line of a file, grep a specific string and make string substitution

I have a file containing more than 14000 records. What I want to do is to process this file line by line and replace a String by anodher string returned by grep command. For example: Line :

/xxxxx/xxxxx/Class.java:67: Logger.w(TAG, "message");

My grep command to get Class.java string is (Class.java is juste an example):

grep -o '[a-zA-Z]*"*\.java"*'

I must, for each line, replace the TAG string by the class.java string return by grep command

Upvotes: 0

Views: 262

Answers (3)

Maroun
Maroun

Reputation: 95968

You can use sed and do the following:

sed -r 's#(.*)/(.*)\.java(.*)(TAG)#\1\/\2\3\2#g'

Characters surrounded with parenthesis are groups that you can use in the second part to get their content.

In order to modify the file in-place, you should:

sed -ir 's#(.*)/(.*)\.java(.*)(TAG)#\1\/\2\3\2#g' your_file.txt

Upvotes: 1

anand mishra
anand mishra

Reputation: 900

You can use:

grep -rl 'old_string' ./ | xargs sed -i 's/old_string/Relacement_String/g'

Upvotes: 0

Hugo G
Hugo G

Reputation: 16496

This is where sed comes in:

sed -i 's/TAG/class.java/g' Class.java

do it for all java files in current directory (assuming bash here):

sed -i 's/TAG/class.java/g' *.java

-i means in-place, so replacing takes place inside the file and is saved immediately. For the rest I suggest you google about sed.

Upvotes: 1

Related Questions