2012-04-22 63 views
1

我想在批處理腳本中「包含」一個數據文件。讓我來解釋一下,我將如何在Unix shell腳本中這樣做,這樣就不會懷疑我想要在批處理腳本中實現什麼。如何在批處理腳本中「包含」數據文件?

#!/bin/bash 
. data.txt # Load a data file. 

# Sourcing a file (dot-command) imports code into the script, appending to the script 
# same effect as the #include directive in a C program). 
# The net result is the same as if the "sourced" lines of code were physically present in the body of the script. 
# This is useful in situations when multiple scripts use a common data file or function library. 

# Now, reference some data from that file. 
echo "variable1 (from data.txt) = $variable1" 
echo "variable3 (from data.txt) = $variable3" 

這是data.txt中:

# This is a data file loaded by a script. 
# Files of this type may contain variables, functions, etc. 
# It may be loaded with a 'source' or '.' command by a shell script. 
# Let's initialize some variables. 
variable1=22 
variable2=474 
variable3=5 
variable4=97 
message1="Hello, how are you?" 
message2="Enough for now. Goodbye." 

在批處理腳本,我的意圖是設置data.txt中的環境變量和「源」該文件在每個批次的我將在後面創建腳本。這也將幫助我通過修改一個文件(data.txt)而不是修改多個批處理腳本來更改環境變量。有任何想法嗎?

回答

3

最簡單的方法是將多個SET命令存儲在data.bat文件中,然後由任何批處理腳本調用該命令。例如,這是data.bat:

rem This is a data file loaded by a script. 
rem Files of this type may contain variables and macros. 
rem It may be loaded with a CALL THISFILE command by a Batch script. 
rem Let's initialize some variables. 
set variable1=22 
set variable2=474 
set variable3=5 
set variable4=97 
set message1="Hello, how are you?" 
set message2="Enough for now. Goodbye." 

到 「源」 在任何腳本這個數據文件,使用:

call data.bat 

Adenddum:途徑 「包括」 的輔助(庫)文件的功能。

「包含」文件的使用函數(子例程)不像變量那麼直接,但可以完成。要在批處理中執行此操作,您需要物理將data.bat文件插入到原始批處理文件中。當然,這可以用文本編輯器完成!

@echo off 
rem Combine the Batch file given in first param with the library file 
copy %1+data.bat "%~N1_FULL.bat" 
rem And run the full version 
%~N1_FULL.bat% 

例如,BASE.BAT:

@echo off 
call :Initialize 
echo variable1 (from data.bat) = %variable1% 
echo variable3 (from data.bat) = %variable% 
call :Display 
rem IMPORTANT! This file MUST end with GOTO :EOF! 
goto :EOF 

DATA.BAT:

但它也可以自動的方式有一個非常簡單的批處理文件名爲source.bat幫助下實現
:Initialize 
set variable1=22 
set variable2=474 
set variable3=5 
set variable4=97 
exit /B 

:display 
echo Hello, how are you? 
echo Enough for now. Goodbye. 
exit /B 

您甚至可以做更復雜的source.bat,因此它會檢查基本庫和庫文件的修改日期,並僅在需要時才創建_FULL版本。

我希望它有幫助...

+0

+1。謝謝。是否可以在data.bat中定義函數,以便這些函數可用於調用data.bat的腳本? – 2012-04-22 15:34:23

+0

@SachinS:見我的答案中的附錄... – Aacini 2012-04-25 02:32:11

+0

謝謝。這真的很好。 – 2012-04-26 13:16:28

1

在DOS批處理文件中沒有自動的方法。您必須在循環中標記文件。例如:

for /f "tokens=1,2 delims==" %i in (data.txt) do set %i=%j 

當然,該行代碼並未考慮樣本data.txt文件中的註釋行。

相關問題