逐行读取一个文件行并更换某些词 [英] Read a file line by line and replace certain words

查看:76
本文介绍了逐行读取一个文件行并更换某些词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有在每一行某些词的文本文件。例如:

I have a text file with certain words in every line. Example:

字1多个字

word15甚至更多的话

word15 even more words

我想要做的就是用某个词来代替的第一个字。例如;如果第一个字是字词1,它将与是,如果在该行的第一个词是word15,它将被替换替换为无。

What I want to do is to replace the first word with a certain word. For example; if the first word is "word1" it will be replaced with "yes" and if the first word in the line is "word15" it will be replaced with "no".

所以我需要一个循环遍历每个行和检查的第一个字,并用某个词替换它。

So I need a loop to go through every line and check the first word and replace it with a certain word.

这是我迄今为止,并没有做任何远程接近我想要做的:

This is what I have so far and it doesn't do anything remotely close to what I want to do:

@ECHO OFF
for /F "tokens=*" %%a in (ukazi.txt) do (
set var=%%a
set new=%var:ls=dir%
set new=$
echo %new%
)
pause

我是新来的一批,我感到困惑越来越多的每一分钟。我将AP preciate帮助了很多!

I'm new to batch and I'm getting confused more and more every minute. I'll appreciate the help a lot!

推荐答案

您可以尝试这样的事:

@echo off
Setlocal EnableDelayedExpansion
for /f "tokens=*" %%i in (c:\temp\word.txt) do call :REPLACE "%%i"

:REPLACE
for /f "tokens=1,*" %%i in (%1) do (
    set test=%%i
    set test=!test:word15=no!
    set test=!test:word1=yes!
    echo  !test! %%j
)

键是:


  • 要使用 EnableDelayedExpansion 这样的变量将在执行时,而不是在脚本的末尾进行扩展(当您使用此,变量将参考使用!变量名!

  • 使用'就地'变量替换(即:%变量名:X = Y%将在变量内容用Y代替每隔X字符)

  • %1 是第一个参数传递给子程序值

  • to use EnableDelayedExpansion so that the variables will be expanded at the execution time rather than at the end of script (when you use this, the variables will be reference using !variable_name!
  • use the 'in-place' variable replacement (ie : %variable_name:X=Y% will replace every X character by Y in the variable content )
  • %1 is the value of the first argument passed to the subroutine

这篇关于逐行读取一个文件行并更换某些词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆