SammuelMiranda
SammuelMiranda

Reputation: 460

Echo each line of a file, skiping X initial character per line

I have a file, with multiple lines that i want to loop each line, skip the first X characters (let's say 8) and echo the rest of the line.

File example:

!        Content i need
!        Other content i need
!        And some other

I'd like to echo "Content i need", "Other content i need" and "And some other" only, skiping the characters from the "!" and it's spaces. It's always X numer of spaces (so, counting the initial symbol and the spaces are 8 characters starting each line of the file).

So far i've done:

for /F "tokens=*" %A in (file.txt) do (echo "%A")

But this happens:

Command Prompt

Tried the Stackoverflow substring command, couldn't make it work (it just adds the command to the end of the echo, and the length of each line is variable, i just know how many initial characters to skip.

Upvotes: 0

Views: 46

Answers (1)

Magoo
Magoo

Reputation: 80183

@ECHO OFF
SETLOCAL

SET "sourcedir=u:\your files"
SET "filename1=%sourcedir%\q79466906.txt"

:: first way
FOR /f "usebackqtokens=1*delims=! " %%b IN ("%filename1%") DO ECHO "%%b %%c"

:: second way thanks to Mofi
FOR /f "usebackqtokens=*delims=! " %%b IN ("%filename1%") DO ECHO "%%b"

GOTO :EOF

The meat of the matter here is the for statement. The rest simply sets variables to suit my environment.

I used a file named q79466906.txt containing your data for my testing.

The usebackq option is only required because I chose to add quotes around the source filename.

Leading delimiters are ignored, so both the Space and ! are skipped. then the next string up to the next delimiter (or delimiter sequence) is assigned to the first metavariable (%%b) and the remainder of the string to %%c.

This works only because the characters-to-be-skipped are leading. The usual syntax would be

set "var=%var:~startposition,endposition%"

where ,endposition is optional, and both numbers are character-counts from the beginning of the string (or end of string if negative)

so you line to remove the first 8 characters would be

set "var=%var:~8%"

But - and this is where the story really begins - you can't substring a metavariable Variables are not behaving as expected

Upvotes: 0

Related Questions