【问题标题】:BASH find and replace in all files in directory using FIND and SEDBASH 使用 FIND 和 SED 在目录中的所有文件中查找和替换
【发布时间】: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"

标签: linux bash sed find


【解决方案1】:

您的“内部”单引号被视为“外部”单引号并导致您出现问题。您认为您在 tr 命令中引用了 |,但您实际上正在做的是结束具有未引用 | 的初始单引号字符串,然后开始一个新的单引号细绳。然后,第二个单引号字符串以您认为正在启动 sed 脚本的单引号结束,而是结束前一个单引号字符串,等等。

如果可以的话,对那些嵌入的单引号使用双引号。如果您不能这样做,则必须使用 '\'' 序列在单引号字符串中获取文字单引号。

【讨论】:

    猜你喜欢
    • 2019-11-29
    • 1970-01-01
    • 2012-08-19
    • 2020-11-15
    • 2011-10-09
    • 2020-02-03
    • 2010-12-20
    • 1970-01-01
    相关资源
    最近更新 更多