Read specific Word(Line 2, Word 3) from a text file by batch script

社会主义新天地 提交于 2019-12-10 11:45:13

问题


I need to read specific words from a text file through batch script. Say I want Line 2 word 3 to be read.

Here is the code::

   @ECHO OFF
    cls
    SET /P line=Please enter Line number: 
    ECHO Line number entered is : %line%

    SET /P word=Please enter Word number: 
    ECHO Word number entered is : %word%


    FOR /F "tokens=%word% skip=%line% delims=," %%G IN (E_dir.txt) DO echo Chosen word is: %%G

The problem is, this gives me all the 3rd words starting from line 2. (say, user input is line 1, Word 3). There is a problem with the line count, But I can handle that. My problem is it is giving me all the words when I need only the single word of Line 2 and word 3.

Input file: E_Dir.txt

January,Snowy,02
February,Rainy,15
March,Sunny,25
April,Test,20

Output:

Please enter Line number: 1
Line number entered is : 1
Please enter Word number: 3
Word number entered is : 3
Chosen word is: 15
Chosen word is: 25
Chosen word is: 20

Expected Output:

Please enter Line number: 1
Line number entered is : 1
Please enter Word number: 3
Word number entered is : 3
Chosen word is: 15

回答1:


Way the first ...

FOR /F "tokens=%word% skip=%line% delims=," %%G IN (E_dir.txt) DO echo Chosen word is: %%G&goto nextline
:nextline

Way the second ...

set showme=Y
FOR /F "tokens=%word% skip=%line% delims=," %%G IN (E_dir.txt) DO if defined showme set showme=&echo Chosen word is: %%G

Amendment

SET /a showme=line-1
SET showme=skip=%showme%
IF %line% equ 1 set "showme= "
FOR /F "tokens=%word% %showme% delims=," %%G IN (E_dir.txt) DO if defined showme set showme=&echo Chosen word is: %%G

Note that where %line% is 1, showme is deliberately set to a SPACE. This ensures that showme has a value initially.

I have no idea where your stray "2" is coming from. The procedure worked for me. Perhaps you may want to check the sourcefile with a hex editor. It may have a line without a LF. Possibly also check your batch. If you've used NOTEPAD, try an editor like EDITPLUS or NOTEPAD++. Notepad does some strange things.



来源:https://stackoverflow.com/questions/18830130/read-specific-wordline-2-word-3-from-a-text-file-by-batch-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!