2010-12-14 68 views
15

我试图找到并替换文件夹中的字符串。找到并替换文件中的字符串

有人可能帮助我吗?

我的脚本如下:

#!/bin/bash 
OLD="This is a" 
NEW="I am a" 
DPATH="/home/user/test/*.txt" 
BPATH="/home/user/test/backup/foo" 
[ ! -d $BPATH ] && mkdir -p $BPATH || : 
for f in $DPATH 
do 
    if [ -f $f -a -r $f ]; then 
    /bin/cp -f $f $BPATH 
    sed "s/$OLD/$NEW/g" "$f" 
    else 
    echo "Error: Cannot read $f" 
    fi 
done 

现在,这似乎找到字符串“这是一个”与“我是”,但这只是打印到屏幕代替。

我需要它来替换文件本身。

感谢

回答

26

使用-i选项sed,以使发生的变化:

sed -i "s/$OLD/$NEW/g" "$f" 
    ^^ 
+0

工作很好!我知道我错过了什么。谢谢 – terrid25 2010-12-14 10:33:56

+0

好的,有没有简单的方法来修改我的shell脚本,以便它将检查子文件夹?/home/user/test/xyz? – terrid25 2010-12-14 10:43:36

+0

#!bin/bash OLD =“这是一个” NEW =“我是” BPATH =“/ home/user/backup/foo” find。 -name'* .shtml'-type f | 同时读取文件名 做 /斌/ CP -f $文件名$ BPATH 使用sed -i “S/$ OLD/$ NEW/G” $文件名 做 – terrid25 2010-12-14 11:28:11

2

输出变为屏幕(stdout)由于下列原因:

sed "s/$OLD/$NEW/g" "$f" 

尝试重定向到一个文件(以下重定向到一个新的文件,然后重命名为覆盖原文件):

sed "s/$OLD/$NEW/g" "$f" > "$f.new" && mv "$f.new" "$f" 
+0

创建一个.text.new文件和原始文件example.txt i被覆盖并且是空白的。任何想法为什么? – terrid25 2010-12-14 10:32:53

+0

@ user390426:可能是因为aix没有引用变量'“$ f.new”'(两个地方)和'“$ f”'。另外,'mv'不应该是无条件的。相反,它应该是'sed ... && mv ...'。 – 2010-12-14 11:07:00

+0

@丹尼斯感谢您的建议。我编辑了这篇文章。 – NPE 2010-12-14 11:26:05

0

这是一个片段我使用,它消除APA和BEPA之间的所有东西(多行,其中包括去除APA,BEPA)我n个电流目录下的所有文件,排除的.svn目录

find . \! -path '*.svn*' -type f -exec sed -i -n '1h;1!H;${;g;s/APA[ \t\r\n]*BEPA//g;p}' {} \; 
0

检查了这一点

http://cs.boisestate.edu/~amit/teaching/handouts/cs-unix/node130.html

########################################################## 
\#!/bin/sh 

\# sed/changeword 

prog=`basename $0` 

case $# in 
0|1) echo 'Usage:' $prog '<old string> <new string>'; exit 1;; 
esac 

old=$1 
new=$2 
for f in * 
do 
     if test "$f" != "$prog" 

     then 
      if test -f "$f" 
      then 
       sed "s/$old/$new/g" $f > $f.new 
       mv $f $f.orig 
       mv $f.new $f 
       echo $f done 
      fi 
     fi 
done 

##############################################################