简体   繁体   中英

How to remove the first and last character from a file using batch script?

This is my input file content which I am using to copy to the output file.

#sdfs|dfasf|sdfs|
sdfs|df!@$%%*&!sdffs|
sasdfasfa|dfsdf|#sdfs|

What I need to do is to omit the first character '#' and last character '|' in the output file. So the output will be,

sdfs|dfasf|sdfs|
sdfs|df!@$%%*&!sdffs|
sasdfasfa|dfsdf|#sdfs

Batch script is new to me, but I tried my best and tried these codes,

:: drop first and last char

@echo off > xyz.txt & setLocal EnableDelayedExpansion

for /f "tokens=* delims=" %%a in (E:\abc1.txt) do (
set str=%%a
set str=!str:~1!
echo !str!>> xyz.txt
)

As you can see it is not able to produce the required output.

The output now being produced is like

sdfs|dfasf|sdfs|
dfs|dfsdffs|
asdfasfa|dfsdf|#sdfs|

I don't know why the string !@$%%*&! is also getting ripped !?

I can't debug my code right now, but try:

:: drop first and last char

@echo off > xyz.txt
@echo off > xyz2.txt
@echo off > xyz3.txt

setLocal EnableDelayedExpansion

for /f "tokens=* delims= " %%a in (E:\abc1.txt) do (
set /a N+=1
echo %%a >> xyz.txt
echo %%b >> xyz2.txt
echo %%%c >> xyz3.txt

Next script, call file far.vbs , anf create your new file.

Code:

set OldFile=E:\abc1.txt
set NewFile=E:\xyz.txt
echo. > "%NewFile%"
start far.vbs "%NewFile%" "%OldFile%"


far.vbs — delete first and last char from file.
Create new file far.vbs in the same folder as first script, and paste the following code:

Set OldFile = CreateObject("Scripting.FileSystemObject")
Set rdOldFile = OldFile.OpenTextFile(Wscript.Arguments(1), 1)
oContent = rdOldFile.ReadAll
rdOldFile.Close

Set lOldFile = CreateObject("Scripting.FileSystemObject")
Set lrdOldFile = OldFile.OpenTextFile(Wscript.Arguments(1), 1)
oLen = len(lrdOldFile.ReadAll)
lrdOldFile.Close

oData = oContent
oData = Right(oContent, oLen-1)
oData = Left(oData, oLen-2)

Set NewFile = CreateObject("Scripting.FileSystemObject")
Set fData = NewFile.OpenTextFile(Wscript.Arguments(0), 2)
fData.WriteLine (oData)
fData.Close

batch is never a strong point for file processing and text manipulation. If you have the luxury, you can download sed from GNU win32, then use this one liner.

C:\test>sed  "/#/{s/^#//;s/|$//}" file
sdfs|dfasf|sdfs
sdfs|df!@$%%*&!sdffs|
sasdfasfa|dfsdf|#sdfs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM