質問

I'm trying to remove the last word of a line in a text file using windows script. Can someone please help me with the code?

I have got a text file test.txt which has the following content

This is a test file union
this is to check union
this is to remove union

I would like to get a batch script to remove the word "union" from the very last line of the textfile. i.e line number 3 (this is to remove union).

Help me please!

Thanks in advance

役に立ちましたか?

解決

Try like this :

@echo off
set "$DelVar=Union"
set "$File=test.txt"

if exist Output.txt del Output.txt
for /f %%a in ('Find /V /C "" ^< %$File%') do set "$Nbligne=%%a"
setlocal enabledelayedexpansion
set "$c=1"
for /f "delims=" %%a in (%$File%) do (
   set "$Line=%%a"
   if !$c!==%$Nbligne% (
      set "$last=%%a"
      set "$Last=!$Last:%$DelVar%=!"
      echo !$Last!>>output.txt
      exit/b
   )
   echo !$Line!>>output.txt
   set /a $c+=1
)

It will create a file Output.txt without the word Union of the last line. You can set the word to remove in the Variable $DelVar and the file to check in $File

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top