Home > Enterprise >  Batch file: Find string in file and write char to beginning of line
Batch file: Find string in file and write char to beginning of line

Time:10-07

I have a .csv file which looks like this:

...
;OUTPUT;DISCRETE;VOLTAGE1;;
;OUTPUT;DISCRETE;VOLTAGE2;;
...

Now I want to search this .csv file for the string for example "VOLTAGE1" and if found, write "#" to the beginning of the line where the search string was found.

So the .csv file should look like this after the batch script finishes:

...
#;OUTPUT;DISCRETE;VOLTAGE1;;
;OUTPUT;DISCRETE;VOLTAGE2;;
...

I already found the way how to search for a string in a file but I don't know how I can write "#" to the beginning of the line in the "do" part of the for loop. So how can I do this?

My code so far:

@echo off
setlocal
for /F "tokens=1* delims=;" %%a in ('findstr /I "VOLTAGE1" file.csv') do <write # to beginning of line>
endlocal

EDIT: The changes should be made to the original .csv file and the script should be called several times with different search strings. Therefore the parameters for the script should be the path to the csv file and the search string.

So in the end each line which contained a seach string should start with a # after several calls of the script

CodePudding user response:

Is powershell an option? e.g.:

ipcsv -d ';' -h a,b,c,d,e,f -pa infile.csv          |
% { if ($_.d -like "voltage1") { $_.a = "#" }; $_ } |
ConvertTo-Csv -d ';' -nti | select -skip 1          |
% { $_ -replace '"','' }

Or ungolfed:

Import-Csv -Delimiter ';' -Header a,b,c,d,e,f -Path infile.csv  |
ForEach-Object { if ($_.d -like "voltage1") { $_.a = "#" } $_ } |
ConvertTo-Csv -Delimiter ';' -NoTypeInformation                 |
Select-Object -skip 1                                           |
ForEach-Object { $_ -replace '"','' }

Output:

#;OUTPUT;DISCRETE;VOLTAGE1;;
;OUTPUT;DISCRETE;VOLTAGE2;;

CodePudding user response:

@echo off
setlocal EnableDelayedExpansion

rem %1 is full file name
rem %2 is search string

set "n="
for /F "delims=:" %%n in ('findstr /N "%~2" %1') do set /A "n=%%n-1"
if not defined n goto :EOF

< %1 (

rem Copy N-1 lines
for /L %%i in (1,1,%n%) do set /P "line=" & echo !line!

rem Modify target line
set /P "line="
echo #!line!

rem Copy the rest
findstr "^" 2>NUL

) > output.csv

move /Y output.csv %1
  • Related