简体   繁体   English

如何在批处理脚本中将特定数据从一个文件复制到另一个文件

[英]How to copy particular data from one file to another in a batch script

I am trying to copy data from a.txt to b.txt using .batch file. 我正在尝试使用.batch文件将数据从a.txt复制到b.txt。 But i dont want the all data from a.txt. 但我不想要来自a.txt的所有数据。 I just trying to copy perticular data. 我只是想复制特定数据。

For Example: a.txt contains 例如:a.txt包含

line 1:this is a.txt file
line 2: name= abc
line 3: age= 24
line 4: country= xyz
line 5: contact no= 123456778
line 6: end of a.txt

Now, I want to read that a.txt and copy particular data to new b.txt: 现在,我想读取a.txt并将特定数据复制到新的b.txt:

b.txt: b.txt:

abc 21 xyz

Any suggestions? 有什么建议么?

Thanks for help. 感谢帮助。

Naren 那仁

Assuming that you meant abc 24 xyz . 假设你的意思是abc 24 xyz (Shortest answer at bottom) (最短的答案在底部)

This provides you with the most flexibility and cleanest variables. 这为您提供了最灵活,最干净的变量。

@echo off
setlocal enabledelayedexpansion

:: Just making sure that %data% is empty
set data=

for /f "tokens=1,2* delims==" %%x in (a.txt) do call :work %%x "%%y"

:: Removes leading space and sends to b.txt
echo %data:~1%>b.txt
goto :eof

:work
set var=%1
set val=%~2

:: Remove any leading spaces.
:work-loop
if "!val:~0,1!"==" " (
  set val=!val:~1!
  goto :work-loop
)

if "%var%"=="name"    set data=%data% %var%
if "%var%"=="age"     set data=%data% %var%
if "%var%"=="country" set data=%data% %var%

goto :eof

Or a little shorter. 或者更短一点。

@echo off
setlocal enabledelayedexpansion

set data=
for /f "tokens=1,2* delims==" %%x in (a.txt) do call :work %%x "%%y"

:: Removes leading space and sends to b.txt
echo %data:~1%>b.txt
echo %data%>b.txt

goto :eof

:work
set var=%1
set val=%~2

:since leading spaces have not been removed, there need be no space between %data% and %var%
if "%var%"=="name"    set data=%data%%var%
if "%var%"=="age"     set data=%data%%var%
if "%var%"=="country" set data=%data%%var%

goto :eof

Shortest answer 最短的答案

@echo off
setlocal
for /f "tokens=1,2* delims== " %%x in (a.txt) do (
    if "%%x"=="name" set %%x=%%y
    if "%%x"=="age" set %%x=%%y
    if "%%x"=="country" set %%x=%%y
)
echo %name% %age% %country%>b.txt
endlocal

In this last one the use of setlocal and endlocal are not ness :: Removes leading space and sends to b.txt echo %data:~1%>b.txt icary, they just make sure your variables die when the batch file ends. 在最后一个中, setlocalendlocal的使用不是ness ::删除前导空格并发送到b.txt echo%data:~1%> b.txt icary,它们只是确保在批处理文件结束时你的变量死掉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM