BASH 使用 FIND 和 SED 查找和替换目录中的所有文件
BASH find and replace in all files in directory using FIND and SED
我需要为目录(包括子目录)中的所有文件查找并替换某些字符串。我想我几乎可以使用以下说明我的一般方法的方法。我在 -exec 中做的不仅仅是这个替换,但为了清楚起见删除了它。
#!/bin/bash
#call with params: in_directory out_directory
in_directory=
out_directory=
export in_directory
export out_directory
#Duplicate the in_directory folder structure in out_directory
cd "$in_directory" &&
find . -type d -exec mkdir -p -- "$out_directory"/{} \;
find $in_directory -type f -name '*' -exec sh -c '
for file do
#Quite a lot of other stuff, including some fiddling with $file to
#get rel_file, the part of the path to a file from
#in_directory. E.g if in_directory is ./ then file ./ABC/123.txt
#will have rel_file ABC/123.txt
cat $file|tr -d '|' |sed -e 's/,/|/g' > $out_directory/$rel_file
done
' sh {} +
一个问题可能是我如何尝试编写文件以通过管道输出。但是,这不是 main/only 问题,因为当我用显式测试路径替换它时,我仍然收到错误
|sed -e 's/,/|/g' |没有那个文件或目录
这让我觉得 cat $file 部分是问题所在?
一如既往地非常感谢任何帮助 - 这只是我必须编写的第二个 BASH 脚本,所以我预计我犯了一个相当基本的错误!
您的 "inner" 单引号被视为 "outer" 单引号并给您带来问题。您认为您在 tr
命令中引用了 |
但实际上您在做的是 ending 具有未引号 [=10= 的初始单引号字符串] 然后开始一个新的单引号字符串。然后,第二个单引号字符串以您认为开始 sed
脚本但结束前一个单引号字符串等的单引号结束,等等
如果可以,请对那些嵌入的单引号使用双引号。如果你不能这样做,你必须使用 '\''
序列在单引号字符串中获取文字单引号。
我需要为目录(包括子目录)中的所有文件查找并替换某些字符串。我想我几乎可以使用以下说明我的一般方法的方法。我在 -exec 中做的不仅仅是这个替换,但为了清楚起见删除了它。
#!/bin/bash
#call with params: in_directory out_directory
in_directory=
out_directory=
export in_directory
export out_directory
#Duplicate the in_directory folder structure in out_directory
cd "$in_directory" &&
find . -type d -exec mkdir -p -- "$out_directory"/{} \;
find $in_directory -type f -name '*' -exec sh -c '
for file do
#Quite a lot of other stuff, including some fiddling with $file to
#get rel_file, the part of the path to a file from
#in_directory. E.g if in_directory is ./ then file ./ABC/123.txt
#will have rel_file ABC/123.txt
cat $file|tr -d '|' |sed -e 's/,/|/g' > $out_directory/$rel_file
done
' sh {} +
一个问题可能是我如何尝试编写文件以通过管道输出。但是,这不是 main/only 问题,因为当我用显式测试路径替换它时,我仍然收到错误 |sed -e 's/,/|/g' |没有那个文件或目录 这让我觉得 cat $file 部分是问题所在?
一如既往地非常感谢任何帮助 - 这只是我必须编写的第二个 BASH 脚本,所以我预计我犯了一个相当基本的错误!
您的 "inner" 单引号被视为 "outer" 单引号并给您带来问题。您认为您在 tr
命令中引用了 |
但实际上您在做的是 ending 具有未引号 [=10= 的初始单引号字符串] 然后开始一个新的单引号字符串。然后,第二个单引号字符串以您认为开始 sed
脚本但结束前一个单引号字符串等的单引号结束,等等
如果可以,请对那些嵌入的单引号使用双引号。如果你不能这样做,你必须使用 '\''
序列在单引号字符串中获取文字单引号。