我需要查找并替换目录(包括子目录)中所有文件的某些字符串。我想我已经接近使用以下方法来说明我的一般方法了。我在 -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 脚本,所以我希望我犯了一个相当基本的错误!
最佳答案
您的“内部”单引号被视为“外部”单引号并给您带来问题。您认为您引用的是 |
在 tr
命令,但您实际上所做的是结束初始单引号字符串,其中包含不带引号的 |
然后开始一个新的单引号字符串。然后,第二个单引号字符串以您认为开始 sed
的单引号结束。脚本,而是结束之前的单引号字符串等。
如果可以的话,对那些嵌入的单引号使用双引号。如果您无法做到这一点,则必须使用 '\''
序列以在单引号字符串中获取文字单引号。
关于linux - BASH 使用 FIND 和 SED 在目录中的所有文件中查找和替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29498696/