【发布时间】:2015-06-12 11:15:57
【问题描述】:
我需要为目录中的所有文件(包括子目录)查找并替换某些字符串。我想我几乎可以使用以下方法来说明我的一般方法。我在 -exec 中做的不仅仅是这个替换,但为了清楚起见,我删除了这个。
#!/bin/bash
#call with params: in_directory out_directory
in_directory=$1
out_directory=$2
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 {} +
一个问题可能是我如何尝试将文件写入管道输出。但是,这不是主要/唯一问题,因为当我用显式测试路径替换它时,我仍然会收到错误 |sed -e 's/,/|/g' |没有那个文件或目录 这让我认为 cat $file 部分是问题所在?
一如既往地非常感谢任何帮助 - 这只是我必须编写的第二个 BASH 脚本,所以我想我犯了一个相当基本的错误!
【问题讨论】:
-
您是否确保您的目标目录存在?
mkdir -p "$out_directory" -
注意引用变量:文件名可以包含空格:
cat "$file" | ... > "$out_directory/$rel_file"