Windows上で、GREPをしたいことがあります。
でも、Windowsは標準で用意してくれていません。
サクラエディタなんかが入れられれば簡単にできますが、
現場によってはフリーウェアが禁止されている場合もあると思います。
でも、Visual Studioは自由に使えるぞ!
って場合に「これさえ打ち込めばGREPが使える」を目指して作りました。
不足した機能があれば追加して使う感じで。
あ、使用は自己責任でお願いします。
using System;
using System.IO;
namespace Grep
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
Usage();
}
else
{
string token = args[0];
string filepath = null;
if (args.Length > 1)
{
filepath = args[1];
}
DoGrep(token, filepath);
}
}
static void DoGrep(string token, string filepath)
{
if (string.IsNullOrEmpty(filepath))
{
int count = 1;
string line;
while ((line = Console.ReadLine()) != null)
{
if (line.IndexOf(token) > -1)
{
Console.WriteLine("{0} : {1}", count, line);
}
count++;
}
}
else
{
try
{
using (StreamReader sr = new StreamReader(filepath))
{
int count = 1;
string line;
while ((line = sr.ReadLine()) != null)
{
if (line.IndexOf(token) > -1)
{
Console.WriteLine("{0} : {1}", count, line);
}
count++;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
static void Usage()
{
Console.WriteLine("使い方: Grep.exe [検索ワード] ([ファイルパス])");
Console.WriteLine("※ファイルパスを省略した場合は標準入力が対象になります。");
}
}
}