배치 파일의 변수에서 큰 따옴표를 제거하면 CMD 환경에 문제가 발생합니다
배치 변수에서 따옴표를 제거하는 효과적이고 안전한 방법을 도울 수 있습니까?
매개 변수 % 1, % 2, % 3 등의 목록을 가져 와서 명명 된 변수에 배치하는 배치 파일을 작성했습니다. 이러한 매개 변수 중 일부는 여러 단어를 포함하므로 큰 따옴표로 묶습니다.
> "Susie Jo" (%1)
> "Smith Barnes" (%2)
> "123 E. Main St." (%3)
다음 % 변수는 명명 된 변수에 배치됩니다.
> set FirstName=%1
> set LastName=%2
> set ShipAddr=%3
변수 확인은 에코로 수행됩니다.
echo. % FirstName %
echo. % LastName %
echo. % ShipAddr %
결과는 다음과 같이 표시됩니다
"Susie Jo"
"Smith Barnes"
"123 E. Main St."
선택한 변수에 포함 된 따옴표를 제거해야합니다. 예를 들어 FirstName과 LastName은 다른 곳에서 사용되며 따옴표를 포함하지 않아야합니다.
테스트 배치 파일에서 변수에 ~ 물결 문자를 사용하여 따옴표를 제거하는 데 성공했습니다.
> set FirstName=%~1
> set LastName=%~2
솔루션이 있다고 생각했지만 곧 배치 파일 실행과 관련하여 비정상적인 동작이 발생했습니다. 갑자기 CMD는 긴 경로 통계를 인식하지 못합니다. 전체 경로에서 배치 파일의 정상적인 실행
> C:\Documents and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat
보고
> 'C:\Documents' is not recognized as an internal or external command....
따라서 ~ % 문자를 들어오는 % 1 % 2 ... % n 변수에 추가하면 약간의 변경이 발생한 것으로 보입니다. 일부 환경 변수가 변경되었을 수 있습니까?
또한 FOR 명령을 사용하여 다양한 시도로 변수 내에서 따옴표를 지우려고했습니다. 그것은 어색해 보였고 작업을 수행 할 변수 목록을 만들어서 이것을 달성하는 방법을 배울 수 없었습니다.
이 같은:
for %%g in (%FirstName% %LastName%) do (
set %%g=%%~g
set %%h=%%~h
set FirstName=%%~g
set LastName=%%h
echo.%FirstName% %LastName%
)
두 가지 문제가 있다고 생각합니다.
1) 들어오는 % 1 % 2 변수 (% ~ 1 등)에 ~ tilde를 삽입하는 '짧고 달콤한'아이디어는 일부 설정에 영향을 미쳤으며 CMD가 긴 경로 이름을 탐색하는 방식을 변경 한 것으로 보입니다.
2) 나는 여전히 선택된 명명 된 변수에서 따옴표를 제거하는 깨끗하고 쉬운 방법을 찾고 있습니다.
더 많은 경험이있는 분들을위한 도움이 있다면 가장 감사하겠습니다. 나는 나의 기술의 끝에서 여기있다. 약간의 안내가 필요하다!
12/26/2009 13:36 PST 전체 배치 파일 편집 :
Blockquote
:: dataout.bat
:: 개정 12/25/2009 ~ % 들어오는 변수를 삽입하여 인용 부호를 제거합니다.
:: 명령 줄 매개 변수를 사용하여 주소 목록
작성 :: QBooks에 대한 데이터 출력 목록
작성 IIF 가져 오기 :: 쓰기 RUI에 대한 판매자 주문 데이터
:: 테스트를위한 샘플 명령 행 문자열
:: listmail [firstname] [lastname] [ "address string"] [ "city string"] [state] [zip] [Order #] [PurchDate] [Regname] [ "이름 성"] [TransactionID] [PaymentMethod] [Total] [ProductID] [Qty] [Price_Each] [PackPrep] [배송] [CommissionPmt] [Invoice #]
:: 예 : dataout Bellewinkle Moose "123 Green Forest Way" "밴쿠버"WA 98664 1004968 05/25/2009 "Bellewinkle Moose" "Olive Oyl"101738 "계정 상"20.67 FK-1P 1 8.95 3.00 1.39 239
@echo off
cls
c :
cd \
cd 문서 및 설정 \ administrator \ my documents \ txt \ batchtest
echo processing % 1 % 2
: VARISET
:: % n 명령 행 매개 변수를 문자열 변수
세트 ($ FirstName) = % ~ 1
세트로 변환 ($ LastName) = % ~ 2
세트 ($ BillingAddress1) = % ~ 3
세트 ($ BillingCity) = % ~ 4
세트 ($ BillingState) = % ~ 5
세트 ($ BillingPostal) = % ~ 6
세트 ($ OrderNumber) = % ~ 7
set ($ Purch_Date) = % ~ 8
set ($ RegistrationName) = % ~ 9
shift
set ($ TransactionID) = % ~ 9
shift
set ($ PaymentMethod) = % ~ 9
shift
set ($ Total) = % ~ 9
시프트 세트 ($ ProductIdentifier) = % ~ 9
시프트
set ($ Quantity) = % ~ 9
shift
set ($ Price_Each) = % ~ 9
shift
set ($ Pack_Prep) = % ~ 9
shift
set ($ Shipping) = % ~ 9
shift
set ($ ServiceFee) = % ~ 9
shift
set ($ Discount) = % ~ 9
shift
set ($ Invoice) = % ~ 9
shift
set ($ UnitPrice) = % ~ 9
set _ShipCombName = % ($ FirstName) % % ($ LastName) %
echo ship combo name은 %입니다 _ShipCombName %
pause
:: 로그 파일에 문자열 변수 쓰기
echo FN % ($ FirstName) % LN % ($ LastName) % BA % ($ BillingAddress1) % % ($ BillingCity) % % ($ BillingState) % % ($ BillingPostal) % % ($ OrderNumber) % % ($ Purch_Date ) % % ($ RegistrationName) % % ($ TransactionID) % % ($ PaymentMethod) % % ($ Total) % % ($ ProductIdentifier) % % ($ Quantity) % % ($ Price_Each) % % ($ Pack_Prep) % % ($ Shipping) % % ($ ServiceFee) % % ($ Discount) % % ($ Invoice) % % ($ UnitPrice) % % _ShipCombName % >> d_out_log.txt
:: 서비스 제공 업체별 계정 할당
IF / i % ( $ PAYMENTMETHOD) % == 아마존 채권 SET _QBAcct = Amazon.com
:: 2009년 12월 25일는 다양성에 대한 제 아마존 pm't 수단을 추가
IF / I % ($ PAYMENTMETHOD) % == 아마존 SET _QBAcct = Amazon.com
/ IF i % ($ PaymentMethod) % == 마스트 세트 _QBAcct = Auth / Net
IF / i % ($ PaymentMethod) % == 마스터 카드 세트 _QBAcct = Auth / Net
IF / i % ($ PaymentMethod) % == 비자 SET _QBAcct = Auth / Net
IF / i % ($ PaymentMethod) % == PayPal SET _QBAcct = PayPalPmts
IF / i % ($ PaymentMethod) % == 계정 SET _QBAcct = % ($ RegistrationName) %
IF / i % ($ PaymentMethod) % == Mail SET _QBAcct = % ($ RegistrationName) %
IF / i % ($ PaymentMethod) % == AMER SET _QBAcct = Auth / Net
IF / i % ( $ PaymentMethod) % == DISC SET _QBAcct = Auth / Net
:: QBAccount
IF / i % ($ PaymentMethod) % == Amazon Receivables SET _Rep = Amazon
:: 12-25-2009 추가 된 두 번째 Amazon 오후에 따라 담당자 지정자 지정 t 다 기능성 방법
IF / i % ($ PaymentMethod) % == 아마존 SET _Rep = 아마존
IF / i % ($ PaymentMethod) % == MAST SET _Rep = BlueZap
IF / i % ($ PaymentMethod) % == MasterCard SET _Rep = BlueZap
IF / i % ($ PaymentMethod) % == 비자 SET _Rep = BlueZap
IF / i % ($ PaymentMethod) % == PayPal SET _Rep = BlueZap
IF / i % ($ PaymentMethod) % == 계정 설정 _Rep = RB
IF / i % ($ PaymentMethod) % == Mail SET _Rep = RB
IF / i % ($ PaymentMethod) % == AMER SET _Rep = BlueZap
IF / i % ($ PaymentMethod) % == DISC SET _Rep = BlueZap
:: 확인 중복 주소 데이터
findstr / i / s "% _ShipCombName %"addrlist.txt
에코 오류 수준 : 오류
수준 1 인 경우 % errorlevel % goto :
오류 수준 0 인 경우 ADDRWRITE
: ADDRFOUND : ADDRWRITE
echo % _ShipCombName % >> addrlist.txt
echo % ($ BillingAddress1) % >> addrlist.txt
에코 % ($ BillingCity) % % ($ BillingState) % % ($ BillingPostal) % >> addrlist.txt
에코. >> addrlist.
echo 주소 파일 작성
: ADDRFOUND
echo selected rep는 % _Rep %
echo 선택된 계정은 다음과 같습니다 : % _QBAcct %
pause
:: RUI OUT
:: 판매자 주문 ID 및 RUI 주문 ID를 RUI에 쓰기
:: writeRUI.txt
CD 에서 중복 RUI 데이터 확인 ..
cd RegKOut
찾기 / i "% ($ OrderNumber) %"writeRUI.txt
에코 오류 수준 : 오류
수준 1 인 경우 % errorlevel % :
오류 수준 0 인 경우 RUIWRITE
: IIFWRITE : RUIWRITE
echo % ($ Invoice) % % ($ OrderNumber) % >> writeRUI.txt
:: 쓰기 RUI
:: IIF OUT
: IIFWRITE
:: writeIIF.txt 에서 중복 된 송장 데이터 확인
찾기 / i "% ($ OrderNumber) %"writeIIF.txt
에코 오류 수준 : 오류
수준 1 인 경우 % errorlevel % goto : HEADWRITE
오류 수준 인 0 인 경우 : LINEWRITE
: HEADWRITE
:: QB IIF 가져 오기 파일에 헤더, 배송 / 처리, 할인, 담당자 및 커미션 데이터 쓰기
에코 % ($ OrderNumber) % % ($ Purch_Date) % 송장 % ($ TransactionID) % % _QBAcct % 매출 채권 % ($ Total) % % _Rep % >> writeIIF.txt
echo H / P % ($ Pack_Prep) % 1? >> writeIIF.txt
echo SHP % ($ Shipping) % 1? >> writeIIF.txt
echo DISC % ($ Discount) % 1? >> writeIIF.txt
echo Comm % ($ ServiceFee) % 1? >> writeIIF.txt
: LINEWRITE
IF / i % ($ ProductIdentifier) % equ PH-1 goto WRITE_DEFA ELSE goto WRITE_DISC
echo % ($ ProductIdentifier) %
: WRITE_DISC
:: 사용자 정의 변수에서 파싱 된 할인 가격을 씁니다.
echo % ($ ProductIdentifier) % % ($ Price_Each) % % ($ Quantity) %? >> writeIIF.txt
goto : EOF
: WRITE_DEFA
: 제품 데이터에서 파싱 된 기본 가격을 기록합니다
echo % ($ ProductIdentifier) % % ($ UnitPrice) % % ($ Quantity) %? >> writeIIF.txt
goto : EOF
:: 3 초 지연
:: TYPE NUL | CHOICE.COM / N / CY / TY, 3> NUL
: EOF
끝에 큰 따옴표가 추가되어 문자열의 끝에 따옴표를 다시 추가합니다 (문자열에서 두 따옴표를 제거한 후).
입력:
set widget="a very useful item"
set widget
set widget=%widget:"=%
set widget
산출:
widget="a very useful item"
widget=a very useful item
참고 : 큰 따옴표 "를 작은 따옴표"로 바꾸려면 다음을 수행하십시오.
set widget=%widget:"='%
참고 : "World"(대소 문자를 구분하지 않음)라는 단어를 BobB로 바꾸려면 다음을 수행하십시오.
set widget="Hello World!"
set widget=%widget:world=BobB%
set widget
산출:
widget="Hello BobB!"
As far as your initial question goes (save the following code to a batch file .cmd or .bat and run):
@ECHO OFF
ECHO %0
SET BathFileAndPath=%~0
ECHO %BathFileAndPath%
ECHO "%BathFileAndPath%"
ECHO %~0
ECHO %0
PAUSE
Output:
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
Press any key to continue . . .
%0 is the Script Name and Path.
%1 is the first command line argument, and so on.
Your conclusion (1) sounds wrong. There must be some other factor at play.
The problem of quotes in batch file parameters is normally solved by removing the quotes with %~ and then putting them back manually where appropriate.
E.g.:
set cmd=%~1
set params=%~2 %~3
"%cmd%" %params%
Note the quotes around %cmd%. Without them, path with spaces won't work.
If you could post your entire batch code, maybe more specific answer could be made.
Spent a lot of time trying to do this in a simple way. After looking at FOR loop carefully, I realized I can do this with just one line of code:
FOR /F "delims=" %%I IN (%Quoted%) DO SET Unquoted=%%I
Example:
@ECHO OFF
SET Quoted="Test string"
FOR /F "delims=" %%I IN (%Quoted%) DO SET Unquoted=%%I
ECHO %Quoted%
ECHO %Unquoted%
Output:
"Test string"
Test string
I usually just remove all quotes from my variables with:
set var=%var:"=%
And then apply them again wherever I need them e.g.:
echo "%var%"
This sounds like a simple bug where you are using %~ somewhere where you shouldn't be. The use if %~ doesn't fundamentally change the way batch files work, it just removes quotes from the string in that single situation.
I learned from this link, if you are using XP or greater that this will simply work by itself:
SET params = %~1
I could not get any of the other solutions here to work on Windows 7.
To iterate over them, I did this:
FOR %%A IN (%params%) DO (
ECHO %%A
)
Note: You will only get double quotes if you pass in arguments separated by a space typically.
- set widget="a very useful item"
- set widget
- widget="a very useful item"
- set widget=%widget:"=%"
- set widget
- set widget=a very useful item"
The trailing quote " in line 4 is adding a quote " to the string. It should be removed. The syntax for line 4 ends with %
I thought I had the solution, but I soon experienced unusual behavior with execution of batch files. Suddenly CMD is no recognizing long path statments. Normal execution of batch file from full path
C:\Documents and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat
returns
'C:\Documents' is not recognized as an internal or external command....
There's your whole problem. CMD doesn't understand spaces inside of filenames from the command line, so it thinks you're trying to pass
and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat
as parameters to the
"C:\Documents"
program.
You need to quote it to run a batch file with spaces in the path:
> "C:\Documents and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat"
would have worked.
@echo off
Setlocal enabledelayedexpansion
Set 1=%1
Set 1=!1:"=!
Echo !1!
Echo "!1!"
Set 1=
Demonstrates with or without quotes reguardless of whether original parameter has quotes or not.
And if you want to test the existence of a parameter which may or may not be in quotes, put this line before the echos above:
If '%1'=='' goto yoursub
But if checking for existence of a file that may or may not have quotes then it's:
If EXIST "!1!" goto othersub
Note the use of single quotes and double quotes are different.
All the answers are complete. But Wanted to add one thing,
set FirstName=%~1
set LastName=%~2
This line should have worked, you needed a small change.
set "FirstName=%~1"
set "LastName=%~2"
Include the complete assignment within quotes. It will remove quotes without an issue. This is a prefered way of assignment which fixes unwanted issues with quotes in arguments.
'Programing' 카테고리의 다른 글
| Haskell에서 "Just"구문은 무엇을 의미합니까? (0) | 2020.08.05 |
|---|---|
| ImportError : dateutil.parser라는 모듈이 없습니다. (0) | 2020.08.05 |
| Spark DataFrame에 새 열을 어떻게 추가합니까 (PySpark 사용)? (0) | 2020.08.05 |
| Java에서 동일한 catch 블록에서 두 가지 예외를 잡을 수 있습니까? (0) | 2020.08.05 |
| C #의 System.Threading.Timer가 작동하지 않는 것 같습니다. (0) | 2020.08.05 |