使用sed脚本格式化txt文件



我有一个文本文件,里面有几百行。这些行中有不同数量的电子邮件地址(都在同一个域中(。我想将这些电子邮件地址的格式从user1@domain.com更改为domainuser1

我尝试对IDs.txt的源文件使用下面的sed脚本,但它出错了,并显示了相应的错误消息:

with open(IDs.txt, '+') as f:
f.write(
re.sub(r'(w+)@domain.com', r'domain\1', f.read())
)

使用以下命令运行脚本:

sed -Ef id.sed 

错误:

sed: file id.sed line 2: unknown command: `f'

从我查到的情况来看,sed甚至可能不会写入文件,所以这可能奏效吗?还是我在浪费时间?谢谢

---编辑---

源文件的示例内容:

set device-group AllPeople TestingPolicy source-user [ name1@domain.com userid@domain.com userid1@domain.com userid3@domain.com ]
set device-group AllPeople TestingPolicy11552 source-user [ userid6@domain.com userid5@domain.com userid4@domain.com userid7@domain.com ]
set device-group AllPeople TestingPolict00988 source-user userid10@domain.com 

预期输出:

set device-group AllPeople TestingPolicy source-user [ domainname1 domainuserid domainuserid1 domainuserid3 ]
set device-group AllPeople TestingPolicy11552 source-user [ domainuserid6 domainuserid5 domainuserid4 domainuserid7 ]
set device-group AllPeople TestingPolict00988 source-user domainuserid10

使用sed

$ sed -E 's/([[:alnum:]]+)@([^.]*)[^ ]*/2\1/g' IDs.txt 
set device-group AllPeople TestingPolicy source-user [ domainname1 domainuserid domainuserid1 domainuserid3 ]
set device-group AllPeople TestingPolicy11552 source-user [ domainuserid6 domainuserid5 domainuserid4 domainuserid7 ]
set device-group AllPeople TestingPolict00988 source-user domainuserid10

使用python

import re
f = open("IDs.txt")
output = re.sub(r'([a-z0-9]+)@([^.]*)[^ ]*', r"2\1", f.read())
print(output)
set device-group AllPeople TestingPolicy source-user [ domainname1 domainuserid domainuserid1 domainuserid3 ]
set device-group AllPeople TestingPolicy11552 source-user [ domainuserid6 domainuserid5 domainuserid4 domainuserid7 ]
set device-group AllPeople TestingPolict00988 source-user domainuserid10

相关内容

  • 没有找到相关文章

最新更新