c#2.0开发的一个文本字符串替换工具,控制台工具,可以批量替换

简介:

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

namespace replace
{

class Program
{
    static void Main(string[] args)
    {

        if (args.Length == 0||(args.Length == 1 && (args[0] == "/?" || args[0] == "?" || args[0] == "-?")))
        {
            Console.WriteLine("replace 命令行工具");
            Console.WriteLine("作者:zj53hao@qq.com");
            Console.WriteLine("CSDN:http://blog.csdn.net/zj53hao");
            Console.WriteLine("用途:在很多需要动态更改某些软件的配置文件时非常有用");
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("replace 命令运用语法阐明");
            Console.WriteLine("  replace [/?|?|-?]    显示帮助信息");
            Console.WriteLine("  replace [path/]filename search replace [/option]  交换文本文件中的字符串,支持通配符文件名");
            Console.WriteLine("  replace setname search replace [/option]  交换参数变量中的字符串");
            Console.WriteLine("/option参数阐明:");
            Console.WriteLine("   i 区分大小写.  默许不区分");
            Console.WriteLine("   r 运用正则表达式查找文本。留空则运用纯文本交换");
            Console.WriteLine("   f 交换文件 默许");
            Console.WriteLine("   v 交换的是系统环境变量.和f不能同时出现");
            Console.WriteLine();
            Console.WriteLine("如: replace *.txt 查找字符串 交换字符串");
            Console.WriteLine("如: replace setname 查找字符串 交换字符串");
            Console.WriteLine("如: replace myinc/*.txt 查找字符串 交换字符串 /i");
            Console.WriteLine("如: replace setname 查找字符串 交换字符串 /irv");
        }
        if (args.Length == 3)
        {
            ReplaceFiles(args[0],args[1],args[2],null);
        }

        if (args.Length == 4)
        {
            if (args[3].Contains("v"))
            {
                ReplaceVariable(args[0], args[1], args[2], args[3]);
            }
            else
            {
                ReplaceFiles(args[0], args[1], args[2], args[3]);
            }
        }

    }

    /// 
    /// 交换环境变量中某个变量的文本值。可以是系统变量,用户变量,临时变量。交换时会覆盖原始值。小心运用
    /// 
    /// 
    /// 
    /// 
    /// 
    public static void ReplaceVariable(string variable, string search, string replace, string options)
    {
        string text=Environment.GetEnvironmentVariable(variable);
        System.Windows.Forms.MessageBox.Show(text);
        text=ReplaceText(text, search, replace, options);
        Environment.SetEnvironmentVariable(variable, text);
        text = Environment.GetEnvironmentVariable(variable);
        System.Windows.Forms.MessageBox.Show(text);
    }
    /// 
    /// 批量交换文件文本
    /// 
    /// 
    public static void ReplaceFiles(string path,string search, string replace, string options)
    {
        
        string[] fs;
        if(File.Exists(path)){
            ReplaceFile(path, search, replace, options);
            return;
        }
        if (Directory.Exists(path))
        {
            fs = Directory.GetFiles(path);
            foreach (string f in fs)
            {

                ReplaceFile(f, search, replace, options);
            }
            return;
        }

        int i=path.LastIndexOf("/");
        if(i<0)i=path.LastIndexOf("/");
        string d, searchfile;
        if (i > -1)
        {
            d = path.Substring(0, i + 1);
            searchfile = path.Substring(d.Length);
        }
        else
        {
            d = System.Environment.CurrentDirectory;
            searchfile = path;
        }

        searchfile = searchfile.Replace(".", @".");
        searchfile = searchfile.Replace("?", @"[^.]?");
        searchfile = searchfile.Replace("*", @"[^.]*");
        //System.Windows.Forms.MessageBox.Show(d);  System.Windows.Forms.MessageBox.Show(searchfile);
        if (!Directory.Exists(d)) return;
        fs = Directory.GetFiles(d);
        foreach (string f in fs)
        {
            if(System.Text.RegularExpressions.Regex.IsMatch(f,searchfile))
                ReplaceFile(f, search, replace, options);
        }
    }
    
    /// 
    /// 交换单个文本文件中的文本
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    public static bool ReplaceFile(string filename, string search, string replace,string options)
    {
        FileStream fs = File.OpenRead(filename);
        

        //判别文件是文本文件还二进制文件。该方法似乎不科学
        byte b;
        for (long i = 0; i < fs.Length; i++)
        {
            b = (byte)fs.ReadByte();
            if (b == 0)
            {
                System.Windows.Forms.MessageBox.Show("非文本文件");
                return false;//有此字节则表示改文件不是文本文件。就不必交换了
            }
        }

        //判别文本文件编码规则。
        byte[] bytes = new byte[2];
        Encoding coding=Encoding.Default;
        if (fs.Read(bytes, 0, 2) > 2)
        {
            if (bytes == new byte[2] { 0xFF, 0xFE }) coding = Encoding.Unicode;
            if (bytes == new byte[2] { 0xFE, 0xFF }) coding = Encoding.BigEndianUnicode;
            if (bytes == new byte[2] { 0xEF, 0xBB }) coding = Encoding.UTF8;
        }

        fs.Close();

        //交换数据
        string text=File.ReadAllText(filename, coding);
        text=ReplaceText(text,search, replace, options);
        File.WriteAllText(filename, text, coding);
        return true;
    }
    /// 
    /// 交换文本
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    public static string ReplaceText(string text, string search, string replace, string options)
    {

        RegexOptions ops = RegexOptions.None;
        if (options == null)  //纯文本交换
        {
            search = search.Replace(".", @".");
            search = search.Replace("?", @"?");
            search = search.Replace("*", @"*");
            search = search.Replace("(", @"(");
            search = search.Replace(")", @")");
            search = search.Replace("[", @"[");
            search = search.Replace("[", @"[");
            search = search.Replace("[", @"[");
            search = search.Replace("{", @"{");
            search = search.Replace("}", @"}");
            ops |= RegexOptions.IgnoreCase;
        }
        else
        {
            if(options.Contains("I"))ops |= RegexOptions.IgnoreCase;
        }

        text = Regex.Replace(text, search, replace, ops);
        return text;
    }
}

}

本文转自博客园知识天地的博客,原文链接:c#2.0开发的一个文本字符串替换工具,控制台工具,可以批量替换 转载请自行联系原博主。

相关文章
|
C#
C#的小例子和字符串(一)
C#的小例子和字符串(一)
322 0
|
开发框架 .NET C#
C#|.net core 基础 - 删除字符串最后一个字符的七大类N种实现方式
【10月更文挑战第9天】在 C#/.NET Core 中,有多种方法可以删除字符串的最后一个字符,包括使用 `Substring` 方法、`Remove` 方法、`ToCharArray` 与 `Array.Copy`、`StringBuilder`、正则表达式、循环遍历字符数组以及使用 LINQ 的 `SkipLast` 方法。
696 8
|
开发框架 .NET 程序员
C# 去掉字符串最后一个字符的 4 种方法
在实际业务中,我们经常会遇到在循环中拼接字符串的场景,循环结束之后拼接得到的字符串的最后一个字符往往需要去掉,看看 C# 提供了哪4种方法可以高效去掉字符串的最后一个字符
1678 0
|
IDE C# 开发工具
一个开源轻量级的C#代码格式化工具(支持VS和VS Code)
一个开源轻量级的C#代码格式化工具(支持VS和VS Code)
742 6
|
SQL Java 测试技术
C#字符串拼接的6种方式及其性能分析对比
在C#编程中字符串拼接是一种常见且基础的操作,广泛应用于各种场景,如动态生成SQL查询、构建日志信息、格式化用户显示内容等。然而,不同的字符串拼接方式在性能和内存使用上可能存在显著差异。今天咱们一起来看看在C#中字符串拼接的常见6种方式及其使用BenchmarkDotNet进行性能分析对比。
639 6
|
程序员 C# 数据库
C# 比较对象新思路,利用反射技术打造更灵活的比较工具
中途接手的项目,碰到需要在更新对象信息时比较并记录差异的需求,最变态的还有附加要求,怎么办?有没有既能满足需求又能对项目影响最小的方法呢?分享这个我封装的方法,一个利用反射技术打造的更灵活的比较工具
476 5
|
前端开发 C#
C# 一分钟浅谈:字符串操作与正则表达式
本文详细介绍C#中的字符串操作与正则表达式应用,涵盖字符串拼接、分割、查找及替换等基础操作,并通过实例讲解正则表达式的模式匹配、文本替换与分组捕获技巧。同时,文章还探讨了性能优化、复杂度管理和安全性等问题及解决策略,助你提升编程效率,应对实际开发挑战。
416 1
|
SQL 开发框架 前端开发
在C#开发中使用第三方组件LambdaParser、DynamicExpresso、Z.Expressions,实现动态解析/求值字符串表达式
在C#开发中使用第三方组件LambdaParser、DynamicExpresso、Z.Expressions,实现动态解析/求值字符串表达式
|
XML 存储 安全
C#开发的程序如何良好的防止反编译被破解?ConfuserEx .NET混淆工具使用介绍
C#开发的程序如何良好的防止反编译被破解?ConfuserEx .NET混淆工具使用介绍
2816 0