Code: Select all
@call jrepl ^
"^(.*?)\t+(.*?)\t+(.*?)\t+(.*?)\t+(.*?)\t+(.*?)\t+(.*?)\t+(.*?)\t+(.*?)\t+(.*)"^
"p($1,2)+p($2,15)+p($3,19)+p($4,4)+p($5,38)+p($6,35)+p($7,13)+p($8,15)+p($9,2)+p($10,10)"^
/jbeg "var sp=' ';function p(str,len) {return (str+sp).slice(0,len);}"^
/jbegln "skip=(ln==1)" /jmatch /f "test.txt" /o "out.txt"
The JREPL solution requires a user supplied function to right pad a string. I really should add some form built in rpad() to the utility.
It is a bit of a pain to hand construct the search and replace strings. Below is an equivalent version that uses batch to build the search and replace strings from a list of field widths. Also, most of the arguments are supplied as variables so the JREPL call is not so ungainly.
Code: Select all
@echo off
setlocal enableDelayedExpansion
:: Define the field widths
set "widths=2,15,19,4,38,35,13,15,2,10"
:: Define the input and output files. Use "-" for output if you want to overwrite the original file.
set "in=test.txt"
set "out=out.txt"
:: Define a function to right pad a string to a given length (this implementation supports up to length 40)
set "beg=var sp=' ';function p(str,len) {return (str+sp).slice(0,len);}"
:: Skip the first line
set "begln=skip=(ln==1)"
:: Prepare the search and replace strings
set "find=^"
set "repl="
set "n=1"
for %%N in (%widths%) do (
set "find=!find!(.*?)\t+"
set "repl=!repl!p($!n!,%%N)+"
set /a n+=1
)
set "find=!find:~0,-5!)"
set "repl=!repl:~0,-1!"
:: Perform the search and replace
call jrepl find repl /v /jmatch /jbeg beg /jbegln begln /f "%in%" /o "%out%"
Dave Benham