Я хочу создать сценарий, который помещает многострочный текст как заголовок в нескольких файлах с txt
расширение. Но текст, который будет вставлен также, включает название файла, в который это будет вставлено.
Здесь идет текст, который будет вставлен:
abcdgd FILENAME dhsgabc
shcnwk shfgamvk
cjshjg nwdcbi
skfh
nwvjcnd
skfh dvwuv
fshvur
egfbt hethtn nhnh
gdngng dehdnnrty
У меня есть много файлов, с именем 001.txt, 002.txt, 003.txt и так далее. NAMEFILE
потребности быть только 001, 002, 003, и так далее (без .txt
расширение).
Необходимо смочь сделать это с простым циклом оболочки по здесь-документу. Например, учитывая файлы 001.txt
к 005.txt
из формы
$ cat 003.txt
=== START OF ORIGINAL FILE 003 ===
stuff
more stuff
even more stuff
затем
for i in {001..005}; do cat - "$i.txt" <<EOF >tmpfile
+++ HEADER $i +++
new stuff
more new stuff
EOF
mv tmpfile "$i.txt"
done
результаты в файлах формы
$ cat 003.txt
+++ HEADER 003 +++
new stuff
more new stuff
=== START OF ORIGINAL FILE 003 ===
stuff
more stuff
even more stuff
и так далее.
Сценарий ниже делает задание рекурсивно.
Используя точно Ваш текст в качестве примера:
#!/usr/bin/env python3
import os
import sys
dr = sys.argv[1]
def addlines(file):
"""
the list below contains the lines, to be added at the top. The lines will
appear in separate lines. In case you want to add an extra line break, use
\n like in the last two lines in the example- content below.
"""
return [
"abcdgd "+file.replace(".txt", "")+" dhsgabc",
"shcnwk shfgamvk",
"cjshjg nwdcbi",
"skfh",
"nwvjcnd",
"skfh dvwuv",
"fshvur",
"\negfbt hethtn nhnh",
"\ngdngng dehdnnrty",
]
for root, dirs, files in os.walk(dr):
for file in files:
path = root+"/"+file
# first read the file and edit its content
with open(path) as new:
text = ("\n").join(addlines(file))+"\n"+new.read()
# then write the edited text to the file
with open(path, "wt") as out:
out.write(text)
Это изменяет файл, названный:
Liesje leerde Lotje lopen.txt
с содержанием:
aap
noot
в:
abcdgd Liesje leerde Lotje lopen dhsgabc
shcnwk shfgamvk
cjshjg nwdcbi
skfh
nwvjcnd
skfh dvwuv
fshvur
egfbt hethtn nhnh
gdngng dehdnnrty
aap
noot
change_file
addlines(file)
текст (но не затрагивают +file.replace(".txt", "")+
. \n
обозначает (n дополнительный) разрыв строки.Выполните его с целенаправленным каталогом как аргумент (каталог с Вашими файлами):
python3 /path/to/change_file /directory
если /directory
включает пробелы, используйте кавычки:
python3 /path/to/change_file '/directory'
Если файлы действительно огромны, мы, возможно, должны были бы оптимизировать процедуру немного в на строку подход, но в средних ситуациях, это должно хорошо работать.