Skip to content

Instantly share code, notes, and snippets.

@Naedri
Last active July 25, 2022 12:13
Show Gist options
  • Save Naedri/87678e8797dce424d342edf700833225 to your computer and use it in GitHub Desktop.
Save Naedri/87678e8797dce424d342edf700833225 to your computer and use it in GitHub Desktop.
To find and replace string in a text.

String operations comparison in Python and Bash

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"SSLProxyEngine On"
test_str = ("areazr\n"
"azraer\n\n\n"
"sdvzer\n"
"zaeraze\n"
"SSLProxyEngine On\n"
"erztaefdaet\n\n"
"SSLProxyEngine On\n\n"
"erztarazed\n"
"azfazerf\n\n"
"eazeazrerezt\n")
matches = re.search(regex, test_str, re.MULTILINE)
if matches:
print ("Correspondance trouvée à la position {start}-{end}: {match}".format(start = matches.start(), end = matches.end(), match = matches.group()))
for groupNum in range(0, len(matches.groups())):
groupNum = groupNum + 1
print ("Groupe {groupNum} trouvé à {start}-{end}: {group}".format(groupNum = groupNum, start = matches.start(groupNum), end = matches.end(groupNum), group = matches.group(groupNum)))
# Note : pour assurer la compatibilité avec Python 2.7, utiliser ur"" comme préfixe d'expression régulière, et u"" comme préfixe de chaîne de test et de substitution.
#!/bin/bash
python
filetosearch = '/home/adrien/Documents/FILA2/Projets/BASH/away/toto.txt'
texttoreplace = 'SSLProxyEngine On'
texttoinsert =
"""
SSLProxyEngine On
Fatoumata
Fatoumati
"""
s = open(filetosearch).read()
s = s.replace(texttoreplace, texttoinsert)
f = open(filetosearch, 'w')
f.write(s)
f.close()
quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment