0

I have a file with records that looks like the following:

Aaron,Daniel,,,AARDA,MEDICAL,10,HEH

I need a batch file that can look to the correct comma and insert quotes as well as add a comma to the end of the file.

I have this batch file which successfully adds quotes to the beginning of each line:

@echo
setLocal EnableDelayedExpansion
for /f "tokens=* delims= " %%a in (input.txt) do (
set /a N+=1
echo ^"%%a >>output.txt
)

What I need is for the output to look like:

"Aaron,Daniel,,",AARDA,MEDICAL,10,HEH,
4
  • What determines the correct comma? Commented Sep 12, 2018 at 15:21
  • Due to the requested output it will always be between the 3rd and 4th comma on every line. Commented Sep 12, 2018 at 15:24
  • Is there a chance that you have more one instance of 3 consecutive commas in each line? or it occurs only once in each line? Commented Sep 12, 2018 at 15:30
  • Hopefully I'm answering your question, the 3 consecutive commas on each line are blank placeholders for each record and will be consistent throughout the whole file. Commented Sep 12, 2018 at 15:32

2 Answers 2

2

As I understood from the comment under your question, the 3 consecutive commas occurs only once in each line. For that matter the solution is extraordinary simple:

@echo off 
setlocal DisableDelayedExpansion
(
    for /F "usebackq tokens=*" %%A in ("input.txt") do (
        set "Line=%%A"
        setlocal EnableDelayedExpansion
        echo "!Line:,,,=,,",!,
        endlocal
    )
)>"output.txt"

It initially starts with delayed expansion off and enables delayed expansion at each iteration of the loop to prevent corrupting lines that contain the ! character.

Since the ,,, occurs only once in each line (As I understood) it can be safely replaced by ,,",

tokens=* is only needed if you want to remove the possible leading white spaces from each line, otherwise you can just use "delims=" to read the whole line in to a single token.

Sign up to request clarification or add additional context in comments.

Comments

1

If an alternative approach is of interest.

With sample file test.txt:

Aaron,Daniel,,,AARDA,MEDICAL,10,HEH
Bob,Edward,,,AARDA,MEDICAL,10,HEH

Using sed, replace the 4th comma with ", and add " at the beginning (^) and , at the end ($):

sed 's/,/",/4' test.txt | sed 's/^/"/' | sed 's/$/,/'

Returns:

"Aaron,Daniel,,",AARDA,MEDICAL,10,HEH,
"Bob,Edward,,",AARDA,MEDICAL,10,HEH,

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.