bash脚本来替换字符串中出现的所有文件,包括文件名 [英] Bash script to replace all occurrences of string in files, including filenames

查看:277
本文介绍了bash脚本来替换字符串中出现的所有文件,包括文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够用另一个替换一个字符串的出现在目录减去的.git目录中的文件的内容,所有文件的文件名。我有以下的code,这有利于改变文件名,但不替换文件内的字符串。我在做什么错了?

I want to be able to replace the occurrences of one string with another in the file contents and filenames of all files within a directory minus the ".git" directory. I have the following code, which is good for changing the filenames but doesn't replace strings inside the files. What am I doing wrong?

#!/bin/bash

# Replace occurances in files, lowercase
lower1=$(echo $1 | tr '[:upper:]' '[:lower:]')
lower2=$(echo $2 | tr '[:upper:]' '[:lower:]')
echo "Replacing $lower1 with $lower2..."
find . -type f \! -iregex '.\|./.git' -exec perl -i -pe 's/$lower1/$lower2/g' {} \;

# Replace all other occurances in files to capitalised
upper2=$(echo ${2:0:1} | tr '[:lower:]' '[:upper:]')${2:1}
echo "Replacing all $1 with $upper2..."
find . -type f \! -iregex '.\|./.git' -exec perl -i -pe 's/$1/$upper2/gi' {} \;

# Replace filenames. Use "bash -c" to pass files as arguments to mv command.
# This worked
find . -name "*$lower1*" -exec bash -c 'mv "$1" "${1/$2/$3}"' -- {} $lower1 $lower2 \;

我也尝试SED,但并没有让不区分大小写。

I did try sed, but that wasn't allowing case insensitivity.

我在OSX山狮测试这一点,如果有差别,但我想这在Linux上正常工作。我是从我的Linux机器走的时刻。

I am testing this on OSX Mountain Lion if that makes a difference, though I do want this to work on Linux as well. I'm away from my Linux machine at the moment.

推荐答案

只需使用 文件::查找

以下code将编辑整个目录树,所以我怎么用它,我会小心。也许有些测试第一? :)

The following code will edit an entire directory tree, so I'd be careful how I used it. Perhaps some testing first? :)

该脚本接受两个字符串作为参数,然后替换的$ string1中所有出现与$字符串2。为了实现完美匹配小写字母,它会以小写$字符串2更换,但对于其他所有的比赛将与大写$字符串2替换。

This script accepts two strings as arguments, and then replaces all occurances of $string1 with $string2. For perfect lowercase matches, it will replace with a lowercase $string2, but for all other matches it will replace with uppercase $string2.

目前,它只是做小写的文件重命名。

Currently, it will just do lowercase for file renames.

use strict;
use warnings;
use autodie;

use File::Find;

die "Usage: $0 From_string To_string\n" if @ARGV != 2;

my ($from, $to) = map lc, @ARGV;

finddepth(sub {
    return if $File::Find::dir =~ /.git\b/;

    # Inplace Edit of files
    if (-f) {
        local @ARGV = $_;
        local $^I = '.bak';
        while (<>) {
            s/\Q$from/$to/g;
            s/\Q$from/\U$to/ig;
            print; 
        }
        #unlink "$_$^I";  # Uncomment if you want to delete backups
    }

    # Rename File
    my $newfile = $_;
    if ($newfile =~ s/\Q$from/$to/ig) {
        rename $_, $newfile;
    }
}, '.');

这篇关于bash脚本来替换字符串中出现的所有文件,包括文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆