2015-04-07 75 views
2

我需要查找并替换目录中所有文件(包括子目录)的某些字符串。我想我差不多用下面的方法来说明我的一般方法。我在-exec里面做的不仅仅是这个替换,而是为了清晰起见删除了这个。BASH使用FIND和SED查找并替换目录中的所有文件

#!/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'|没有这样的文件或目录 这使我认为猫$文件的一部分是问题?

任何帮助一如既往地受到大众的欢迎 - 这只是我写过的第二个BASH脚本,所以我期望我已经犯了一个相当基本的错误!

+0

您是否确定您的目的地目录存在? 'mkdir -p“$ out_directory”' –

+1

注意引用你的变量:文件名可以包含空格:'cat“$ file”| ...>“$ out_directory/$ rel_file”' –

回答

3

您的“内部”单引号被视为“外”单引号引起您的问题。您认为您在命令中引用了|,但您实际上在做什么是结尾具有未引用的|的初始单引号字符串,然后启动新的单引号字符串。然后,第二个单引号字符串以单引号结尾,您认为该引号是开始sed脚本,而不是结束先前的单引号字符串等。

如果可以,请为这些嵌入的单引号使用双引号。如果你不能这样做,你必须使用'\''序列来得到单引号字符串中的文字单引号。

相关问题