Learner
Learner

Reputation: 159

Unix Command to find and replace a string in multiple files under nested directory

I need to find file naming with app.properties and replace the string "username" with "user".

I did achieved that by this

find . -type f  -name 'app.properties' -print0 | xargs -0 sed -i '' -e  's/username/user/g'

But i want to see the changes as well in a file as an output of that command , how can i do that ?

Upvotes: 0

Views: 217

Answers (2)

Cole Tierney
Cole Tierney

Reputation: 10324

Bash process substitution can be used as a dry run without creating temp files.

Original file:

cat
bird
dog

Dry run sed command:

diff file <(sed 's/bird/frog/' file)
2c2
< bird
---
> frog

Here's a bash script that reads paths from stdin and applies the sed dry run. A sed pattern can be passed as an optional parameter.

#!/bin/bash

pattern=${1:-s/bird/frog/}

while read -r path; do
    echo "$path:"
    diff "$path" <(sed "$pattern" "$path")
    echo
done

Example with default pattern:

find dir* -type f -name file\* | ./sed-dry-run.sh

Output:

dir1/file1:
2c2
< bird
---
> frog

dir2/file2:
2c2
< bird
---
> frog
4c4
< bird
---
> frog

Example with a pattern as an argument:

find dir* -type f -name file\* | ./sed-dry-run.sh 's/bird/dinosaur/'

Output:

dir1/file1:
2c2
< bird
---
> dinosaur

dir2/file2:
2c2
< bird
---
> dinosaur
4c4
< bird
---
> dinosaur

Upvotes: 1

l0b0
l0b0

Reputation: 58988

Use sed -i '.bak' … to create a app.properties.bak file with the original content, then you can use diff to see the differences.

Upvotes: 1

Related Questions