2
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WSHで文字列置換&上書き

Posted at

WSHで特定の文字列を置換して上書きするやつ。

アイコンの上にCSVファイルをドラッグすると特定の文字列を置換して上書きするスクリプト。

「システムAからシステムBにインポートするときに、表記揺れを正さなきゃいけない。ファイル名は毎日変わる。テキストエディタでの一括置換は人的ミスが心配。作業者のPCスキルも低い。」とかいう限定用途向け。

意外に探してもなかったので置いておきます。

文字列一括置換.vbs
Option Explicit

Dim objArgs 'Argumentsオブジェクト生成用変数
Dim objFileSys 'FileSystemオブジェクト生成用変数
Dim objFile 'ファイル展開
Dim strExt '拡張子確認用
Dim strTmp '一時データ格納用
Dim MSG '処理確認

Set objArgs = WScript.Arguments

If objArgs.Count = 1 Then
	Set objFileSys = CreateObject("Scripting.FileSystemObject")
	
	'拡張子がcsvの時処理開始
	strExt = objFileSys.GetExtensionName(objArgs(0))
	If strExt = "csv" Then
		
		MSG = msgbox("下記のように置換します" & vbNewLine &  "AAA → BBB" & vbNewLine &  "CCC → DDD" & , vbOKCancel)
	
		'OKの時は処理を進める
		If MSG = vbOK Then
		
			Set objFile = objFileSys.OpenTextFile(objArgs(0))
		
			'ファイル読込
			strTmp = objFile.ReadAll
			'replaceの第2引数の文字列を第3引数の文字列へ置換する。
			'好き放題増やしてもよい
			strTmp = replace(strTmp,"AAA","BBB")
			strTmp = replace(strTmp,"CCC","DDD")
			objFile.Close
		
			'書込
			Set objFile = objFileSys.CreateTextFile(objArgs(0))
			objFile.WriteLine (strTmp)
		
			objFile.Close
			
			'オブジェクトの破棄
			Set objArgs = Nothing
			Set objFileSys = Nothing
			Set objFile = Nothing
			
			msgbox "成功"
		
		End If	
	Else	
		'ファイルがcsvじゃなかった時
		msgbox "処理できるのはcsvのみです"
		End If
	Else
		'ファイルが複数の時、アイコンをダブルクリックされた時
		msgbox "対象のファイルを1つずつドラッグ&ドロップしてください" 
End If

BATでよくない?

少し前に作ったものなので仔細を覚えてないけど、DOSコマンドに文字列置換がないから、という理由でWSHを選んだんだと思う。

2
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?