T3RRYT3RR0R

Substitute lines of text by line #

Jan 2nd, 2020
373
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Batch 1.53 KB | None | 0 0
  1. @ECHO OFF
  2. Color 02
  3.  
  4. TITLE Text Substitution by Line Number
  5. Setlocal EnableDelayedExpansion
  6.  
  7. :select
  8. cls
  9.  
  10. Set /p "inputfile=[Type or paste full filepath, or drop file If no Spaces:]>"
  11. IF not defined inputfile goto select
  12.  
  13. REM - Test existance of file, return to select if not exist
  14. IF NOT exist "%inputfile%" GOTO select
  15.  
  16. REM - Capture info to rename temp file with later
  17.  
  18. for /f "delims=" %%a in ("%inputfile%") do (
  19.     Set inputfile=%%a
  20.     Set name=%%~na
  21.     Set Location=%%~dpa
  22.     Set EXT=%%~xa
  23. )
  24.  
  25. Set "TempReplaces=!Location!!name!!EXT!"
  26.  
  27. REM - Count number of lines in file
  28.  
  29. Set avail=0
  30. REM - Check available lines:
  31. for /f "delims=" %%a in (%inputfile%) do (
  32.     set /a avail+=1
  33. )
  34.  
  35. REM - Select Line Number
  36.  
  37. :linenumber
  38. cls
  39. ECHO File: %inputfile%
  40. Set /p subline=[File Contains: %avail% Lines. Line Number to Substitute:]
  41.  
  42. REM - Ensure the linenumber is numerical
  43.  
  44. Set /a test=%subline%+1
  45. IF %test% LSS 2 GOTO linenumber
  46.  
  47. REM - Enter Replacement String
  48.  
  49. Set /p substitution=[Enter Replacement Text:]
  50.  
  51. REM - Function counts lines then Echoes the defined text when target line is encountered.
  52.  
  53. for /f "delims=" %%l in (%inputfile%) do (
  54.     set /a line+=1
  55.     if !line! EQU !subline! (
  56.         echo %substitution% >>%Location%TempSub%EXT%
  57.     ) else (
  58.         echo %%l >>%Location%TempSub%EXT%
  59.     )
  60. )
  61.  
  62. REM - Replace File With Substitution
  63. DEL /Q "%TempReplaces%"
  64. DEL /Q "%TEMP%\inputfile.txt"
  65. TIMEOUT 1 > nul
  66. FOR %%n IN ("%Location%TempSub%EXT%") DO (
  67. REN %%n "%name%!EXT!"
  68. )
  69.  
  70. ECHO Done
  71. TIMEOUT 2 > nul
  72. EXIT
Advertisement
Add Comment
Please, Sign In to add comment