Unix命令在嵌套目录下的多个文件中查找和替换字符串

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

我需要找到以app.properties命名的文件并将字符串“username”替换为“user”。

我确实做到了

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

但是我想在文件中看到更改作为该命令的输出,我该怎么做?

使用sed -i '.bak' …创建一个包含原始内容的app.properties.bak文件,然后您可以使用diff查看差异。

Bash 进程替换可以用作干 运行 而无需创建临时文件。

原文件:

cat
bird
dog

干运行 sed命令:

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

这是一个 bash 脚本,它从标准输入读取路径并应用 sed dry 运行。 sed 模式可以作为可选参数传递。

#!/bin/bash

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

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

默认模式示例:

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

输出:

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

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

以模式作为参数的示例:

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

输出:

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

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