How i can Insert filename inside it in batch

Viewed 42

I have a few thousand txt files and I need to insert the filename inside each one between <> on the second line. For example: I have lot of files like this

    225248F040.txt
    225248F060.txt
    225248F070.txt
    225446F020.txt...

Their content header:

    %
    (PROGRAM.....225248F040)
    (PROGRAMMER.....NAME)
    (DATE....... 28.APR.2022)
    (TIME............. 10.26)
    (MACHINE........DX250)
    (================================)

I need to add the name between <> on the second line of each one, looking like this:

    %
    <225248F040.txt>
    (PROGRAM.....225248F040)
    (PROGRAMMER.....NAME)
    (DATE....... 28.APR.2022)
    (TIME............. 10.26)
    (MACHINE........DX250)
    (================================)

I can use CMD, Bash linux, Powershell or Python.

2 Answers
path_to_file = '/home/user/Documents/path_to_file.txt'

with open(path_to_file) as f:
    source_contents = f.read()
    source_splitlist = source_contents.split('\n')

if len(source_splitlist) > 0:
    source_splitlist.insert(1, f'<{path_to_file}>')
    destination_altered = '\n'.join(source_splitlist)

    with open(path_to_file, 'w') as f:
        f.write(destination_altered)

else:
    print('Not happy, file to short')
@ECHO OFF
SETLOCAL
rem The following settings for the directories are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.

SET "sourcedir=u:\your files"
SET "destdir=u:\your results"

FOR /f "delims=" %%b IN (
 'dir /b /a-d "%sourcedir%\*" '
 ) DO (
 set "inserted="
 for /f "usebackqdelims=" %%e in ("%sourcedir%\%%b") do (
 echo %%e
 if not defined inserted echo ^<%%b^>
 set "inserted=y"
 )
)>"%destdir%\%%b"


GOTO :EOF

Always verify against a test directory before applying to real data.

Simply read each line from each file, and insert the required data (filename in %%b) after the first line, using inserted as a switch to determine whether the extra data has already been inserted.

Related