Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

Append to the first and last line of files

I have many files, and need help with a batch file to add a comma, and press ENTER.

I merge files together and what happens is first.txt and second.txt
merge into one.txt file

This is the script I use

type *.txt > files
ren "files" "All Files.txt"

and when I do, this happens

{
"dash": 123,
"bash": 123,
"cash": 123,
}{
"dash": 123,
"bash": 123,
"cash": 123,
}

Since I have many files I have to go after every last } add a , and press enter
so when I merge them together this should happen

{
"dash": 123,
"bash": 123,
"cash": 123,
},
{
"dash": 123,
"bash": 123,
"cash": 123,
},

Now I was given this script

for %%i in (*.txt) do >>%%i echo ,

and this adds the comma , to the last } and some how it presses enter


So now I run this script

for %%i in (*.txt) do >>%%i echo ,

type *.txt > files
ren "files" "All Files.txt"

The results of this is what I am looking for

{
"dash": 123,
"bash": 123,
"cash": 123,
},
{
"dash": 123,
"bash": 123,
"cash": 123,
},

Thank you everyone

question from:https://stackoverflow.com/questions/65557889/append-to-the-first-and-last-line-of-files

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You cold try something like this.

@echo off

set "opts=usebackq tokens=* delims="
set "file=path_to_yourfile.txt"
for /f "%opts%" %%i in ("%file%") do (
    for /f "tokens=* delims=" %%a in ('echo %%i^| findstr /b ")"') do (
        echo(%%i,
        goto:skip
    )
    echo(%%i)
):skip

Still not clear enough what you would like to do with that (ENTER). Try it and see if it is what you're looking for.

If this is not the case, what you can try after is to add echo. after echo(%%i,, i.e.

echo(%%i,
echo.

EDIT:

OK, so you can add the comma at the same time as you append the single file to the Merged one:

@echo off

if exist "pathDATAMERGED.txt" del "pathDATAMERGED.txt"
pushd "C:folderwhereyouhaveallxtfiles"
for /f "tokens=1,2,* delims=" %%a in ('dir /b^| findstr /e ".txt"') do (
    >>"pathDATAMERGED.txt" (type %%a &&echo ,)
)
popd

This adds a comma after you typed each file.

BTW, you should absolutely try to be more clear and precise when you explain what you would like to do.

In fact, you say you want to move by 4 spaces something (either { or }, IT IS NOT CLEAR to me..). I guess than that this comes from the formatting of your single text files, so why didn't you format the the right way if this is the case?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...