红联Linux门户
Linux帮助
当前位置: 红联Linux门户 > Ubuntu

将一个目录下的所有文件内容里的某个字符串a更改为字符串b的实现

发布时间:2011-09-03 14:56:11来源:红联作者:wfc1102
#!/bin/bash
#Program: This program is to replace the specific string within documents in a dir
#History: 2011-09-03 wfc First Release
dir_in=/home/lasg/work ###################################
cd $dir_in
# 1) get the names of these documents in the dir
names=`ls -l | cut -d ' ' -f 8` ; echo "the documents are:${names}"
echo "-----------------------------------------------------------"
# 2)replace the specific string and > to new document
dir_out=/home/lasg/work2 ##########
sudo mkdir -p $dir_out
# defaults: please make sure only documents in dir,if not, you may do it like this:
# during 1) the names are printed on the screen, you may copy them to here
# for name in `here` ######### like: for name in `doc1 doc2 doc3`
# and add # to the line below
for name in ${names} ###########################
do
new=$name; echo $new
touch $dir_out/$new
# this is an example: replace 'o' with 'oo'#######################
cat $name |sed 's/o/oo/g'> $dir_out/$new ;
unset new
echo "-----------------------------------------------------------"
done
文章评论

共有 3 条评论

  1. wfc1102 于 2011-09-04 13:40:51发表:

    lykginy的代码十分简洁,在此表示感谢。
    功能上,使得多重子目录下的文档内容可以一并替换,
    LZ把代码重新整理如下:

    #!/bin/bash
    dir=/home/user/work
    for i in `find $dir -maxdepth 2 -type f` ### -maxdepth n表示dir 下有几重子目录,没有时n=1,依此类推
    do
    sed 's/a/b/' $i > $i.new
    done

  2. lykginy 于 2011-09-03 17:14:29发表:

    for i in `find dir -maxdepth 1 -type f`; do sed 's/a/b/' $i > $i.new; done

  3. Goando 于 2011-09-03 16:26:00发表:

    路过