How can you find and replace character in a text file in Windows command-line line by line but from a specific character appear count?

Related searches

I have a text file with a semicolon separator (CSV), it has 65 columns but the last is a "comments" column that can have semicolons in his body. I would like to know how to write a windows batch file that count the semicolons in every line and if it finds > 64 semicolons, deletes all the semicolons that follow after 64 (or change with a comma). (I don´t have access to the source that builds the texts files)

Example actual:

marshal;Stevens;Son;11223344;Dual;this person tries food; water; fruit

Expected output:

marshal;Stevens;Son;11223344;Dual;this person tries food, water, fruit
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
SET "filename1=%sourcedir%\q56171667.txt"
SET "outfile=%destdir%\outfile.txt"
FOR /f "usebackqtokens=1*delims=" %%a IN ("%filename1%") DO (
 SET "line=%%a"
 CALL :lop64


:: remove the first 64 ;-terminated strings from LINE
:: remove remaining `;`

SET /a lopoff=64
SET "original=%line%"
SET "line=%line:*;=%"
SET /a lopoff-=1
IF %lopoff% gtr 0 GOTO lop64lp
CALL ECHO %%original:;%line%=%%;%line:;=%
GOTO :eof

You would need to change the settings of sourcedir and destdir to suit your circumstances.

I used a file named q56171667.txt containing some dummy data for my testing.

Produces the file defined as %outfile%

The usebackq option is only required because I chose to add quotes around the source filename.

Text-processing in batch is a minefield. You're probably better-off using sed or (g)awk which are designed for the task.

I'm assuming for lack of information otherwise that your data does not contain characters that have a special meaning to batch like % or " or & or | or < or > amongst others.

Essentially, assign the entire line read to line, then in the subroutine, substitute nothing for each string up to a ; (:*;=) 64 times. Then show the original string, with the remainder in line substituted by nothing concatenated with ; and line's remainder with ; substituted with nothing (:;=). If you want commas in place of semicolons, use :;=, here.

How to find the number of occurrences of a string in file using , So you are counting the lines resulting from your findstr command that do not per line, so in this case the above works, but multiple addresses per line To avoid the file name in the output, change it to this: It is very small and safe text filter. The caret sign(^) acts as escape character in windows batch� Although we can’t directly search and replace text inside a text file, we can do the next best thing. We can: 1) open up a text file; 2) read the text into a variable; 3) do a search-and-replace on that variable; and 4) re-save the text file. We can even do all that from the command line, although we’ll hold off on that for a moment.

Although you did not show any own efforts to solve your task, I decided to provide some code, because it is a nice challenge – see all the explanatory rem remarks:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_FILE=%~1"  & rem // (input file; `%~1` is the first command line argument)
set "_SEP=;"     & rem // (original separator to be replaced)
set "_NEW=,"     & rem // (new separator to replace the old one with)
set /A "_LIM=64" & rem // (number of first original separators to be kept)

rem // Read input file line by line:
for /F usebackq^ delims^=^ eol^= %%L in ("%_FILE%") do (
    rem // Store current line, reset some auxiliary variables:
    set "LINE=%%L" & set "COLL=" & set /A "CNT=-1"
    setlocal EnableDelayedExpansion
    rem // Handle the case when no original separator is defined:
    if defined _SEP (
        rem // Iterate through all separated items of the current line:
        for %%I in ("!LINE:%_SEP%=" "!") do (
            rem // Support loop to transport `COLL` variable over `endlocal` barrier:
            for /F "delims=" %%J in (""!COLL!"") do (
                rem /* Store currently iterated item, increment item counter and
                rem    store rebuilt line with separators replaced as defined: */
                set "ITEM=%%~I" & set /A "CNT+=1" & set "COLL=%%~J"
                setlocal EnableDelayedExpansion
                rem // Check whether or not to exclude current separator:
                if !CNT! gtr %_LIM% (
                    set "COLL=!COLL!!_NEW!!ITEM!"
                ) else if !CNT! gtr 0 (
                    set "COLL=!COLL!!_SEP!!ITEM!"
                ) else set "COLL=!ITEM!"
        rem // Return rebuilt line with separators replaced as defined:
    ) else echo(!LINE!

exit /B

Given the script is saved as repl-sep.bat and the input file is called 1.csv, run the script as follows:

repl-sep.bat "1.csv"

To store the output to a file called 2.csv rather than to display it in the console, use this command line:

repl-sep.bat "1.csv" > "2.csv"

Regard that the following characters must not occur in the input file: ?, *, <, >, ".

Find - Search for text - Windows CMD, /C Count the number of lines containing the string. /N Display Line numbers. /I Ignore the case of characters when searching for the string. [/off[line]] Do not skip � Remove text after a specific character from each line in a text file. To remove text after a specific character — e.g., a hyphen, from each line in a text file, use: Find what: (.+)\s*-\s*(.+) Replace with: $1; Set the Search mode to Regular expression; Uncheck matches newline; Click Replace All::Before::

Ideally you would read in the file with a for /f and use "tokens=64*delims=;" to get the remainder of the line and only substitute semicolons in there.

Sadly the maximum tokens value is 31 (plus * remainder), so you've to nest several for /F

:: Q:\Test\2019\05\16\SO_56171667.cmd
@Echo off
Set "FileIn=Col65.csv"
Set "FileOut=NewCol65.csv"

(    for /F "usebackq  delims="  %%a in ("%FileIn%"
) do for /F "tokens=31*delims=;" %%b in ("%%a"
) do for /F "tokens=31*delims=;" %%d in ("%%c"
) do for /f "tokens=2* delims=;" %%f in ("%%e"
) do Call :Sub "%%a" "%%g"

Goto :Eof
Set "Line=%~1#"
Set "Col65=%~2"
Set "Col65=%Col65:;=,%"
Call Echo:%%Line:%~2#=%Col65%%%

Aside from loading time this PowerShell script might be faster with larger files:

## Q:\Test\2019\05\16\SO_56171667_2.ps1
$FileIn  = 'Col65.csv'
$FileOut = 'NewCol65.csv'
Get-Content $FileIn | ForEach-Object{
  $Cols = $_ -split ';',65
  $Cols[-1] = $Cols[-1].Replace(';',',')
  $Cols -join ';'
} | Set-Content $FileOut

to be on topic wrapped in a batch:

:: Q:\Test\2019\05\16\SO_56171667_2.cmd
@Echo off
Set "FileIn=Col65.csv"
Set "Fileout=NewCol65.csv"

powershell -NoP -C "gc '%FileIn%'|ForEach-Object{$Cols=$_ -split ';',65;$Cols[-1]=$Cols[-1].Replace(';',',');$Cols -join ';'}|Set-Content '%FileOut%'"

Findstr - Search for strings - Windows CMD, Search for a text string in a file (or multiple files) unlike the simple FIND command /A:color Display filenames in colour (2 hex digits) options can be any /P Skip any file that contains non-printable characters /OFF[LINE] Do not skip files words (assuming you have not specified a literal search with /C) but this might not � If you want to find specific text in files, in a command line output or elsewhere, you may use the findstr command on Windows to do so. Findstr is a built-in tool of the Windows operating system that you may run from the command line to find text in files or in command line outputs.

Find and replace in text files with UltraEdit, This button will count the number of occurrences of your search string in the active file. All open files – If you select this option, repeating the find next command you to search for strings that are different, but still match of a specific pattern. in our search string tells UltraEdit to find any character that is not a new line, and� By default, Windows uses WScript to execute VBScript (VBS) files. The only problem this can cause is any errors and/or messages from the script will appear as popup boxes. For a command line tool, it is best these messages be displayed in the console. There are a couple of ways you can accomplish this.

How to Use the Find Command to Search in Windows, Windows has some built-in search capabilities, but they may not be to Opening the Command Prompt window as administrator is not You could also search all text files in a directory using the wildcard character, To display only the number of lines in the text file (not the lines Count number of lines� This small script doesn't do in-place replacement, meaning that you would have to save new text to new file, and get rid of the old file, or mv new.txt old.txt Side note: if you're curious about why while IFS= read -r ; do done < input.txt is used, it's basically shell's way of reading file line by line.

Need to know how to use PowerShell to read a text file and replace text? This is what we call the PowerShell Read-Text File. Look no further! This blog post is for you. By the end of the post, I’ll show you a function I built to make your life much easier. Replacing text in a file with PowerShell is three-step process. Reading the file

  • Considering that this site is not a free code writing service, your question appears to be a request for one. Please edit your question to include the code you want us to help you to fix, and a full explanation of how it fails to work as written and intended.
  • Using JREPL.BAT - jrepl ";" "," /p "^((?:[^;]*;){64})(.*;)" /prepl "$1+{$2}" /f "input.csv" /o -
  • First, my apologies for not post any code because sincerely my attempts really su**s but i'm glad to be able to learn, i will try all the solutions that were kindly provided by all of you. Thanks!