The easiest method is using REPL.BAT written by Dave Benham.
type "input.txt" | repl.bat "[ \t]+(?:(\|)|$)" "$1" >"output.csv"
The search regular expression [ \t]+(?:(\|)|$)
means:
[ \t]+
... find 1 or more spaces or horizontal tabs.
(?:
...)
... non marking/capturing group for the OR expression inside this group.
(\|)|$
... find a literal interpreted pipe character and capture this character if really found OR end of line without matching the newline characters.
The replace regular expression $1
references the found pipe character if there was one found by the search expression at all.
In other words this regular expression finds 1 or more spaces or tabs left to a pipe character and removes those whitespaces OR finds trailing spaces/tabs at end of a line and removes them too.
Use next the command move /Y "output.csv" "input.txt"
to overwrite the input file with the produced output file.
It is of course also possible to use latest version of JREPL.BAT also written by Dave Benham.
To write the output to output.csv
:
jrepl.bat "[ \t]+(?:(\|)|$)" "$1" /f "input.txt" /o "output.csv"
To do the replaces directly on input file:
jrepl.bat "[ \t]+(?:(\|)|$)" "$1" /f "input.txt" /o -
You have to use command CALL on calling either repl.bat
or jrepl.bat
when you need more to do and therefore those command lines are used within your batch file. In this case I suggest to use instead of just repl.bat
or jrepl.bat
:
... call "%~dp0repl.bat" ...
call "%~dp0jrepl.bat" ...
The batch file for the replace operation is called now with full path of your batch file. repl.bat
or jrepl.bat
must be stored in the directory of your batch file. Then it does not matter what is the current directory on running your batch file.
Even better would be the usage of search regular expression string [ \t]+(?=\||$)
which uses an OR expression in a lookahead expression to produce a positive match for 1 or more spaces/tabs only when next character is the pipe character or the spaces/tabs are found at end of line. The replace string is in this case simply an empty string as only the spaces/tabs are matched by the search string.
Example:
call "%~dp0jrepl.bat" "[ \t]+(?=\||$)" "" /f "input.txt" /o -