简体   繁体   English

BASH使用FIND和SED查找并替换目录中的所有文件

[英]BASH find and replace in all files in directory using FIND and SED

I need to look for and replace certain strings for all files in a directory, including sub-directories. 我需要查找并替换目录中所有文件的某些字符串,包括子目录。 I think I'm nearly there using the following method which illustrates my general approach. 我想我几乎可以使用以下方法说明我的一般方法。 I do much more inside the -exec than just this replace, but have removed this for clarity. 我在-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 {} +

One issue is likely how I've tried to write the file to pipe the output to. 一个问题可能是我如何尝试写入文件以将输出传递到。 However, this isn't the main/only issue as when I replace it with an explicit test path I still get the error |sed -e 's/,/|/g' |No such file or directory which makes me think the cat $file part is the problem? 但是,这不是主要/唯一的问题,因为当我用显式的测试路径替换它时,我仍然收到错误| sed -e's /,/ | / g'|没有这样的文件或目录,这使我认为cat $ file部分是问题吗?

Any help is massively appreciated as always - this is only the second BASH script I've ever had to write so I expect I've made a fairly basic mistake! 任何帮助都一如既往地受到高度赞赏-这只是我必须编写的第二个BASH脚本,因此我希望我犯了一个相当基本的错误!

Your "inner" single quotes are being seen as "outer" single quotes and causing you problems. 您的“内部”单引号被视为“外部”单引号,并给您带来麻烦。 You think you are quoting the | 您认为您正在引用| in the tr command but what you are actually doing is ending the initial single-quoted string having an unquoted | tr命令中,但实际上是在结束以单引号引起来的无引号|字符串| and then starting a new single-quoted string. 然后开始一个新的单引号字符串。 That second single-quoted string then ends at the single-quote that you believe is starting the sed script but is instead ending the previous single-quoted string, etc. 然后,该第二个单引号字符串以您认为正在启动sed脚本的单引号结束,而结束了先前的单引号字符串,等等。

Use double quotes for those embedded single quotes if you can. 如果可以,对那些嵌入的单引号使用双引号。 Where you can't do that you have to use the '\\'' sequence to get a literal single-quote in the single-quoted string. 在无法执行此操作的地方,您必须使用'\\''序列在单引号引起来的字符串中获取文字单引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM