G. Jonathan
G. Jonathan

Reputation: 74

substring windows command line

I tried to get the substring from each line of a text file based on fixed position in the file. I would like to achieve that using command lines.

My file look like this:

45testing45
46testing46
47testing47
48testing48
49testing49
50testing50
51testing51
52testing52
53testing53

I tried the following command line:

For -F %i in (inputFile.txt) do (SET _line=%i SET _chars=%_line:~10,2% @echo _chars > outputFile.txt)

But the result is that the outputFile.txt is created but empty and when I hit SET in the command prompt, I see the _line variable as such _line=53testing53 SET _chars=%_line:~10,2% @echo _chars > outputFile.txt) I do not get why, I suppose I miss a delimiter in the DO part so that I can separate the different SET command.

Could you please help me get the last 2 digits of my file in a new output file? I have downloaded Cygwin so am open to Unix command as well but I do not understand how to extract a fixed length substring of each line of a file using sed or awk.

Thanks in advance.

Upvotes: 1

Views: 15262

Answers (3)

user9952217
user9952217

Reputation:

Actually, you do not really need Cygwin in Windows if you wanna solve this quest with sed (see this repo for the details). After downloading and placing sed's binary in the PATH variable you can type in the command prompt next command:

sed -r "s/.*([0-9]{2})/\1/" input.txt > output.txt

and it'll be done. You can find online sed's manual page here. Pure cmd script:

@echo off
  setlocal enabledelayedexpansion
    set "f=C:\files\input.txt"
    >C:\files\output.txt (for /f %%i in (%f%) do (
      set "l=%%i"
      echo !l:~-2!
    ))
  endlocal
exit /b

Upvotes: 0

Compo
Compo

Reputation: 38654

This may work for you:

(For /F %A In (inputFile.txt) Do @Set "_=%A"&Call Echo ^%_:~-2^%)>outputFile.txt

Upvotes: 2

Mike Schlueter
Mike Schlueter

Reputation: 41

You have a couple of typos, and I put it into a script.

For /F %%i in (inputFile.txt) do (CALL :DisplaySubString %%i)
GOTO :EOF

:DisplaySubString
SET _line=%1 
SET _chars=%_line:~9,2% 
@echo %_chars% >> outfile.txt

One problem is that you're trying to process variables within (). You would need to use DelayedExpansion to do that.

To get around that, I made a "subroutine" in the .cmd file called :DisplaySubString.

Your indexing was off by one, 10 -> 9.

@echo %_chars% was missing the %

You have to use >> instead of > to append to the file as you go.

Upvotes: 0

Related Questions