2017-08-22 8 views
0

私は簡単な質問があります。.txtファイルの.batファイル変数をキャッチ

変数を.batファイルから.txtファイルに渡すことはできますか?私がオンラインで見つけられるのは、ファイルの末尾に変数を追加するか、.txtファイル全体を上書きすることだけです。 {0}、{1}の可変キャッチャーなどを.txtファイルに入れておくことはできますか?.batコマンドを使用すると、実行時にこれらの特定の場所の.txtファイルに変数を送信できますか?

もし可能であれば、.txtファイルを上書きして自分の変数をこれらの場所に自分自身で含めるだけでよいのであれば、一般的に不思議です。

+2

これは、テキストファイルテンプレート内の特定の文字列のためのバッチ変数を置換することが可能ですが、容量が限られており、使いにくいです。必要なテキストに "poison characters"( 'cmd'と特別な意味を持つもの)がない場合は、これを行うことができますが、' sed'や 'g )awk'。それにもかかわらず、単純な代替のために、はい、できます。 – Magoo

答えて

1

あなたは

template.txt

The element !data1! refers to !data2! 

Also, the element !data3! points to !data4! 


You will need to escape exclamations 
    Escaped exclamation  : ^! 
    Non escaped exclamation : ! 

; 
;   !data4! 
; 

@echo off 
    setlocal enableextensions disabledelayedexpansion 

    rem Define the set of data that will be replaced 
    set "data1=TEST" 
    set "data2=This is the data in || TEST ||" 

    set "data3=Another test!" 
    set "data4=< data inside [Another test!]>" 

    rem Read template (uses findstr /n to retrieve empty lines) 
    for /f "delims=" %%a in ('findstr /n "^" "template.txt"') do (
     rem Retrieve line 
     set "line=%%a" 

     rem To retrieve the data in line var we need delayed expansion 
     setlocal enabledelayedexpansion 

     rem Output template line after removing initial numbers 
     rem On empty lines the for command "fails". This is detected and 
     rem handled by echoing an empty line 
     (for /f delims^=^ eol^= %%b in ("!line:*:=!") do echo(%%b)||echo(

     rem Cancel delayed expansion 
     endlocal 
    ) 

コンソールをprocess.cmd似た何かを得るためにバッチファイルで変数展開のプロセスを "虐待" することができます出力

W:\45820941>process 
The element TEST refers to This is the data in || TEST || 

Also, the element Another test! points to < data inside [Another test!]> 


You will need to escape exclamations 
    Escaped exclamation  : ! 
    Non escaped exclamation : 

; 
;   < data inside [Another test!]> 
; 

W:\45820941> 
関連する問題