Jaf*_*son 4 command-line awk text-processing
我在一个文件夹中有许多文本文件。其中的文本格式如下:
%%%%%%%%%%@yahoo.com
%%%%%%@wanadoo.fr
%%%%raviplywoodglasscentre@yahoo.comravi
%%nameemail%%@yahoo.com
%.getincontact@numberland.com
%0dronbracale@roadrunner.com
%1%3@example.com
%1@elsewhere.com
%1@example.com
Run Code Online (Sandbox Code Playgroud)
我想对所有文件文本进行更改并使它们如下所示:
{"email":"%%%%%%%%%%@yahoo.com"}
{"email":"%%%%%%@wanadoo.fr"}
{"email":"%%%%raviplywoodglasscentre@yahoo.comravi"}
{"email":"%%nameemail%%@yahoo.com"}
Run Code Online (Sandbox Code Playgroud)
我想制作这样的完整文件,它们位于文件夹中。
我试过这个:
awk '{ printf("{"email":"%s"}", $l);}' test
Run Code Online (Sandbox Code Playgroud)
但它没有用。
那么,有什么方法可以修改文件夹中所有文件中的文本吗?
$ sed 's/.*/{"email":"&"}/' file
{"email":"%%%%%%%%%%@yahoo.com"}
{"email":"%%%%%%@wanadoo.fr"}
{"email":"%%%%raviplywoodglasscentre@yahoo.comravi"}
{"email":"%%nameemail%%@yahoo.com"}
{"email":"%.getincontact@numberland.com"}
{"email":"%0dronbracale@roadrunner.com"}
{"email":"%1%3@example.com"}
{"email":"%1@elsewhere.com"}
{"email":"%1@example.com"}
Run Code Online (Sandbox Code Playgroud)
所以要对你可以做的所有文件采取行动
sed -i 's/.*/{"email":"&"}/' *
Run Code Online (Sandbox Code Playgroud)
保留旧文件的副本
sed -i.old 's/.*/{"email":"&"}/' *
Run Code Online (Sandbox Code Playgroud)
-i.old 就地修改文件而不是打印到标准输出,并在修改前使用扩展名保存每个文件的副本 .olds/old/new替换old为new.* 行上的任何字符& 匹配的模式无疑更冗长,但要编辑目录中的所有文件:
如果目录是平面的:
#!/usr/bin/env python3
import os
import sys
dr = sys.argv[1]
for file in [os.path.join(dr, f) for f in os.listdir(dr)]:
newtext = "\n".join(['{"email":"'+l.strip()+'"}'for l in open(file).readlines()])
open(file, "wt").write(newtext)
Run Code Online (Sandbox Code Playgroud)如果目录是递归的,并且您还需要转换子目录中的文件:
#!/usr/bin/env python3
import os
import sys
dr = sys.argv[1]
for root, dirs, files in os.walk(dr):
for file in files:
file = os.path.join(root, file)
newtext = "\n".join(['{"email":"'+l.strip()+'"}'for l in open(file).readlines()])
open(file, "wt").write(newtext)
Run Code Online (Sandbox Code Playgroud)在这两种情况下,文件的内容都变为:
{"email":"%%%%%%%%%%@yahoo.com"}
{"email":"%%%%%%@wanadoo.fr"}
{"email":"%%%%raviplywoodglasscentre@yahoo.comravi"}
{"email":"%%nameemail%%@yahoo.com"}
{"email":"%.getincontact@numberland.com"}
{"email":"%0dronbracale@roadrunner.com"}
{"email":"%1%3@example.com"}
{"email":"%1@elsewhere.com"}
{"email":"%1@example.com"}
Run Code Online (Sandbox Code Playgroud)
edit_files.py以目录为参数运行它:
python3 /path/to/edit_files.py /path/to/files_to_convert
Run Code Online (Sandbox Code Playgroud)这是假设所有行内的所有文件需要进行编辑。请说明我们是否需要为其中一个或两个设置条件。