1

I need to write a script file, that iterates over all files in a given start folder recursivly.

Within each file it then should replace a string.

The files look like the following

...

( value1= "FOO")
...
...
( value2= "BAR")
...

FOO and BAR are different for each file, but I want to replace the string of value2 (in this case BAR) with the string of value1 (in this case FOO).

4
  • 3
    So what do you have so far? What worked? What did not? Commented Dec 27, 2016 at 17:59
  • Is it important that value2 remains in the same place in the file? Commented Dec 27, 2016 at 18:03
  • 1
    Take a look at sed and find. Come back when you have code that does not work for some specific reason. SO is not a free code-writing service. Commented Dec 27, 2016 at 18:04
  • Might wanna take a look at awk and grep as well Commented Dec 27, 2016 at 18:10

1 Answer 1

1

Something like this works! Using GNU grep for identifying the search pattern and perl for in-place replacement.

#!/bin/bash

while IFS='' read -r -d '' filename
do
    value1=$(grep -oP '(?<=value1=\s").*(?=")' "$filename")
    value2=$(grep -oP '(?<=value2=\s").*(?=")' "$filename")
    perl -pi.bak -e "s/\( value1= ".*"\)/(\ value1= \"$value2\"\)/;" -e "s/\( value2= ".*"\)/(\ value1= \"$value1\"\)/" "$filename"        
done < <(find . -maxdepth 1 -type f -print0)

Remove the -i.bak once to see if the replacement file is displayed properly in stdout, once confirmed add the flag back.

Sign up to request clarification or add additional context in comments.

2 Comments

Can't you just do something like this: find . -type f -exec grep 'variable1' {} | awk -F\" '{print $2}' | xargs sed command here; ?
@dramzy : Appreciate your suggestion. I always use the -print0 option to find files with space or special characters in them for a more robust handling. Anyway mine looks more readable, easy to maintain I guess.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.