批处理文件文本编辑

时间:2017-07-03 16:02:58

标签: batch-file

我正在尝试制作一个批处理文件,要求用户输入员工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

2 个答案:

答案 0 :(得分:0)

由于file被引用,您需要usebackq上的for /f选项,否则它将被视为要由for /f分析的字符串,而不是文件。

BTW - !var!仅在变量值可能在块内发生变化时才需要(例如,带有循环)。如果该值不会发生变化,请使用%var%(例如,file中的for /fidsearch内的raise(但似乎不是从发布的代码初始化)但 "%filename%",因为这是循环操作的一部分。

我保留引用的值(通常用于文件名)但引号是必需的(例如,包含空格的文件名)然后我引用变量,例如 func keyframeAnimate () { UIView.animateKeyframes(withDuration: 3, delay: 0, options: [], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1.0, animations: { let translation = CGAffineTransform(translationX: 150, y: 150) self.square.alpha = 0.5 self.square.transform = translation.rotated(by: CGFloat.pi).scaledBy(x: 2, y: 2) }) UIView.addKeyframe(withRelativeStartTime: 1.01, relativeDuration: 1.0, animations: { let translation = CGAffineTransform(translationX: 100, y: 400) self.square.alpha = 1 self.square.transform = translation.rotated(by: -CGFloat.pi).scaledBy(x: 1, y: 1) }) }) } 。遵循这个方案可能会更容易。

答案 1 :(得分: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

这次没有评论。

请理解,如果您的搜索文件的布局发生更改,这些脚本可能无效!