1.

Solve : Get a substring from the file?

Answer»

I have one file 'filename.txt' which have contents like

SHCS112.txt
SHCQ112.txt
SHMSTR114.txt
CQCS113.txt
CSCQ114.txt

I have to read the contents and move it to different file according to their name.

For example, the name which is having "CS" in 3-4 range should be moved to another file

Example:

SHCS112
CQCS113
should be moved to cs_files.txt

similarly, the name which is having "CQ" in 3-4 range should be moved to another file
SHCQ112
CSCQ114
should be moved to cq_files.txt

I used findstr "cs" filename.txt> cs_file.txt
but it is reading

SHCS112
CQCS113
CSCQ114----- wrong out put

give me idea to move the files according to their name.Flying blind without a mention of an OS can be tricky, but this may work on your machine:

Code: [Select]@echo off
setlocal enabledelayedexpansion
for /f %%i in (filename.txt) do (
set var=%%i
set var=!var:~2,2!
if !var!==CS echo %%i >> cs_files.txt
if !var!==CQ echo %%i >> cq_files.txt
)

You never mentioned where the MS file goes.

Good luck. 8-)I am using Windows XP operating system. The code that you have given is not working.

Code:

set var='SHCS112.txt'
set var=!var:~2,2!
echo %var%

Result:
!var:~2,2!

It does not take 3rd and 4th characters from that VARIABLE. My result should print 'CS'.
Please guide me to solve this issue.
Actually the code works fine on my machine, also XP.

Quote

set var='SHCS112.txt'
set var=!var:~2,2!
echo %var%

Where did the SINGLE quotes come from? Although they would not prevent the batch file from functioning properly there is no mention of them in the original post.

It should be echo !var! due to the delayed expansion

8-)Hi,
This is my screen shot of my command window.
------------------------------------------------------------------------
C:\>setlocal enabledelayedexpansion

C:\>set var=SHCS112.txt

C:\>set var=!var:~2,2!

C:\>echo !var!
!var!
-------------------------------------------------------------------------
My result is !var!

Please help me in solving this as I am new to WRITING Batch Script.






Cut and Paste this code into your favorite editor (notepad works just fine):

Code: [Select]@echo off
setlocal enabledelayedexpansion
for /f %%i in (filename.txt) do (
set var=%%i
set var=!var:~2,2!
if !var!==CS echo %%i >> cs_files.txt
if !var!==CQ echo %%i >> cq_files.txt
)

Save the file with any name you choose but be sure to give it a .bat EXTENSION. You can then run the file you SAVED from the command line.

8-)Hi,

Thanks a lot for guiding me. Its really awesome. I got the exact result.
This is really a wonderful site which makes me do the task easily.

Thanks a lot!
Thanks a lot!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


Discussion

No Comment Found