Solved how to find and replace a number subjected to a condition

March 30, 2014 at 10:59:15
Specs: windows7, P4 4GB
I have a situation where I need to find if a particular number is occurring in a specific location subjected to the occurrence of another number in the same line at another fixed location. If both the above condition is meet , replace the first number with a new value.
For example in the below value, I want to replace "2112" to "1551" which is occurring at 13,14,15 &16 location in the line , provided the number occurring at 3,4,5&6th location is 1456.

-----------------------------------------------------
12345678901234567890123456789
-----------------------------------------------------
0012000001 21120180 10303410
0014560001 21120180 10303411

So after executing the bat file I will get below output

-----------------------------------------------------
12345678901234567890123456789
-----------------------------------------------------
0012000001 21120180 10303410
0014560001 15510180 10303411


See More: how to find and replace a number subjected to a condition

Report •

#1
March 30, 2014 at 13:17:31
D:\test>type file.txt
-----------------------------------------------------
12345678901234567890123456789
-----------------------------------------------------
0012000001 21120180 10303410
0014560001 21120180 10303411

D:\test>perl -pi.bak -e "s/^(\d\d1456\S+) 2112/$1 1551/" file.txt

D:\test>type file.txt
-----------------------------------------------------
12345678901234567890123456789
-----------------------------------------------------
0012000001 21120180 10303410
0014560001 15510180 10303411


Report •

#2
March 31, 2014 at 01:50:24
✔ Best Answer
::====== script starts here ===============
:: chg 2112 to 1551 in line containing 1456 [?!]
:: 1456.bat 2014-03-31 15:34:37.15
@echo off > NEWFILE & setLocal enableDELAYedeXpansioN

:main
for /f "tokens=1* delims=[]" %%a in ('FIND /N "1456" ^< myfile') do (
set L=%%a
)

:sub1
set N=
for /f "tokens=* delims= " %%i in (myfile) do (
set/a N+=1
set S=%%i
if !N! equ !L! set S=!S:2112=1551!
echo.!S!
) >> NEWFILE
goto :eof
::====== script ends here =================

=====================
M2 Golden-Triangle


Report •
Related Solutions


Ask Question