Home > Back-end >  Formatting txt file with sed script
Formatting txt file with sed script

Time:09-17

I have a text file with a few hundred lines in it. In those lines are varying numbers of email addresses (all of the same domain). I want to change those email addresses from the format of [email protected] to domain\user1.

I tried using the below sed script against the source file of IDs.txt, but it errored out with the corresponding error message:

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

Ran script with this command:

sed -Ef id.sed 

Error:

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

From what I looked up sed may not even write to files, so is this even possible to work or am I wasting time? Thanks.

---EDIT---

Sample contents of the source file:

set device-group AllPeople TestingPolicy source-user [ [email protected] [email protected] [email protected] [email protected] ]
set device-group AllPeople TestingPolicy11552 source-user [ [email protected] [email protected] [email protected] [email protected] ]
set device-group AllPeople TestingPolict00988 source-user [email protected] 

Expected output:

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

CodePudding user response:

Using sed

$ sed -E 's/([[:alnum:]] )@([^.]*)[^ ]*/\2\\\1/g' IDs.txt 
set device-group AllPeople TestingPolicy source-user [ domain\name1 domain\userid domain\userid1 domain\userid3 ]
set device-group AllPeople TestingPolicy11552 source-user [ domain\userid6 domain\userid5 domain\userid4 domain\userid7 ]
set device-group AllPeople TestingPolict00988 source-user domain\userid10

Using 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 [ domain\name1 domain\userid domain\userid1 domain\userid3 ]
set device-group AllPeople TestingPolicy11552 source-user [ domain\userid6 domain\userid5 domain\userid4 domain\userid7 ]
set device-group AllPeople TestingPolict00988 source-user domain\userid10
  • Related