繁体   English   中英

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=$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脚本的单引号结束,而结束了先前的单引号字符串,等等。

如果可以,对那些嵌入的单引号使用双引号。 在无法执行此操作的地方,您必须使用'\\''序列在单引号引起来的字符串中获取文字单引号。

暂无
暂无

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

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