'Replace text using Python
I am attempting to replace text from a source file into a new file. The replacing of text works for one line, but a few lines down and I fail to replace text sitting in the middle of a statement.
Here is the source text. The words in brackets are what I am trying to replace, without changing the characters around the words:
[set interfaces] ge-0/0/0 [description] "OoB Mgmt Connection"
This is what I would like to output:
interface x/x name"xxx" (also adding quotations for the xxx text after "name")
Edit:
However the output text replaces once, but then keeps copies of the original text:
set interfaces ge-0/0/0 description "OoB Mgmt Connection"
set interfaces ge-0/0/0 description "OoB Mgmt Connection"
interface 1/1 name "OoB Mgmt Connection"
set interfaces ge-0/0/0 enable
set interfaces ge-0/0/0 enable
interface 1/1 enable
set interfaces ge-0/0/0 unit 0 description "EX4300-mgmt-1;10.30.41.14;ge-0/0/6\\n"
set interfaces ge-0/0/0 unit 0 description "EX4300-mgmt-1;10.30.41.14;ge-0/0/6\\n"
Here is my code:
with open("SanitizedFinal_E4300.txt", "rt") as fin:
with open("output6.txt", "wt") as fout:
for line in fin:
fout.write(line.replace('set system host-name EX4300', 'hostname "EX4300"'))
fout.write(line.replace('set interfaces ge-0/0/0 unit 0 family inet address', 'ip address'))
Please let me know where I went wrong or if there is a better way of approaching this. I am using Visual Studio Code.
Solution 1:[1]
You could try using regular expressions, i.e. re.sub() (https://docs.python.org/3/library/re.html#re.sub). In your example this snipped should work:
import re
fixed_line = re.sub(r'\[set interfaces\] ge-([^ ]*)[^"]*("[^"]*")',
r'interface \1 name \2',
'[set interfaces] ge-0/0/0 [description] "OoB Mgmt Connection"'
)
where: r'[set interfaces] ge-([^ ])[^"]("[^"]*")' defines pattern to be catched, with two capturing groups (in round parentheses). Then matched string is replaced with string interface \1 name \2, where \1 and \2 are references to captured groups.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Maciej Wrobel |
