Txt files merging while adding file name extensions

45 Views Asked by At

96467,2

96466,3

93015,1

4466,1

90721,1

96239,1

96241,1

93024,1

Hey guys, I hope you are all fine. I have numerous text files containing lists similar to the one shown above. Previously, I ought to merge these lists into a single text file using the command-line script:

copy *.txt merged_file.txt 

Now, I want to improve this process by appending the names of the respective text files next to each item when copying them to the new merged file. The desired output format should have each item followed by the name of the file it originated from, separated by a hash sign (#). For clarity, the format should look like this:

96467,2#19.txt

96466,3#19.txt

93015,1#19.txt

4466,1#19.txt

90721,1#KAfa.txt

96239,1#KAfa.txt

96241,1#KAfa.txt

93024,1#KAfa.txt

93022,1#Tall.txt

I appreciate any kind of help.

I expect that my issue be solved through command line commmand without the use of python.

2

There are 2 best solutions below

2
Gilles Quénot On BEST ANSWER

What I would do:

for file in *.txt; do
    echo "$(<"$file")#$file" | tee new_file.txt
done
cat new_file.txt
1
Hasan Mougharbel On

I had finally succeeded to accomplish this through a bat file, below is my code

@echo off
setlocal enabledelayedexpansion

REM Create an empty merged file
type nul > merged_file.txt

REM Loop through each text file
for %%f in (*.txt) do (
    REM Extract filename without extension
    set "filename=%%~nf"
    
    REM Append each line with filename to merged file
    for /f "tokens=*" %%i in (%%f) do (
        echo %%i#!filename!.txt>> merged_file.txt
    )
)

echo Merging completed.