2017-07-03 171 views
0

我正在尝试创建一个批处理文件,要求用户输入员工ID和他们希望增加员工工资的金额。为此,我必须为使用用户输入的ID的员工更改.txt文件的工资字段。下面是我目前使用的代码,但我似乎无法得到任何地方,因为它只是吐出错误。批处理文件文本编辑

REM Prompt the user for the ID they wish to search 
set /p idSearch=Enter the employee's ID number: 
set /p raise=Enter the raise ammount: 
echo. 

REM Set the file to search 
set file="employees.txt" 

setlocal ENABLEDELAYEDEXPANSION 

for /f "tokens=1-5 delims=," %%i in (!file!) do (
if %%i=="ID: !idSearch!" (
set /a new_amount=%%s+!raise! 
echo ID: %%i FIRST: %%f LAST: %%l AGE: %%a Salary: $!new_amount! 
) else (
echo ERROR 
) 
) 
pause 

这里是什么在.txt文件的例子:

ID: 20 FIRST: John LAST: Smith AGE: 30 SALARY: $20000

+0

对于显示的数据行,由于行中没有逗号,整行将被分配给'%% i'。如果您要删除'delims'子句,将使用默认空间,'%% i'将获得'ID:','%% j'' 20','%% k'' FIRST:'等等。这似乎不会与您使用的'echo'结婚。 – Magoo

+0

除了@Magoos评论和回答没有货币变量类型,所以你不能使用set/a与一个美元符号开始的字符串。在你的文件的每一行都有字段名是非常低效的。 – LotPings

+0

@Magoo我已经得到了它的工作感谢您的帮助,但是当我尝试将其保存到文本文件时,它将删除文件中的任何其他员工。你有什么建议如何解决这个问题? – Brett

回答

0

由于file被引用,则需要在for /fusebackq选项,否则这将是视为一个字符串,由for /f进行分析,而不是文件。

顺便说一句 - !var!只有当变量的值可能在一个块内(例如,一个循环)发生变化时才需要。如果该值不会改变,使用%var%(例如,filefor /fidsearch块内(但它似乎不从张贴的代码初始化),但不raise,因为这是作为其一部分变化环的操作。

我把报价从分配(通常为文件名)的值,但在报价方面的要求(如:包含空格的文件名),那么我引用变量,如"%filename%"。按照该方案可能会更容易。

0

我会用唯一的$字符作为分隔符:

@Echo Off 
Rem Enable Delayed Expansion 
SetLocal EnableDelayedExpansion 
Rem Set the file to search 
Set "file=employees.txt" 
Rem Exit if search file does not exist 
If Not Exist "%file%" Exit/B 
Rem Prompt the user for the ID they wish to update 
Set/P "id=Enter the employee's ID number: " 
Rem Search file for input ID 
For /F "Tokens=1* Delims=$" %%A In ('Find "ID: %id% "^<"%file%"') Do (
    Rem Show the user the current salary value 
    Echo Current Salary for ID %id% is $%%B 
    Rem Prompt the user for the new raise amount 
    Set/P "raise=Press Enter to accept or Type an increase amount: " 
    Rem Supplement 0 raise for empty amount 
    If Not Defined raise Set "raise=0" 
    Rem Calculate new salary based on raise 
    Set/A "new_amount=raise+%%B" 
    Rem Output line with resultant salary 
    Echo %%A $!new_amount! 
) 
Timeout -1 
GoTo :EOF 

你当然可以删除注释行。

编辑

下面是其写入新文件的版本。我感到慷慨...

@Echo Off 
SetLocal EnableDelayedExpansion 
Set "file=employees.txt" 
If Not Exist "%file%" Exit/B 
Set/P "id=Enter an employee ID number: " 
If Not Defined id Exit/B 
Set/P "amount=Enter new raise increase: " 
If Not Defined amount Set "amount=0" 
(For /F "UseBackQDelims=" %%A In ("%file%") Do (Echo=%%A|Find "ID: %id% ">Nul&&(
    For /F "Tokens=1* Delims=$" %%B In ("%%A") Do (Set/A "amount+=%%C" 
     Echo=%%B$!amount!))||Echo=%%A))>updated.txt 

这次没有评论。

请理解,如果您的搜索文件的布局更改这些脚本可能无法正常工作!

+0

这可行,但是如果在文本文件中有其他员工将其删除,并且只是让他们的工资发生变化的员工 – Brett

+0

否,它不会,我的脚本只回显到控制台的一行;你已经改变了一些东西导致了这个问题。 _最佳猜测是你已将'Echo %% A $!new amount!'重定向到一个文件._ – Compo

+0

是的,整个文件的目的是用新文件取代当前那个工资。对不起,如果我以前没有提及。所以我将它设置为输出到.tmp文件,然后将其复制到employees.txt文件。 – Brett