Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace specific string using sed

Tags:

linux

bash

unix

sed

I have a code.txt file that contains morse code for example

.- .-.

I have a function called decode inside a bash file called morse as this:

decode (){ 
   sed -i 's/ \.-/A/g' $1
   sed -i 's/ \.-./R/g' $1
   cat $1
}

When I type in terminal $bash morse decode code.txt

I receive:

AA.

The output I want is :

AR

How can it see separate that the string .- is A and the .-. is R?

like image 725
P.Bes Avatar asked Jun 21 '26 22:06

P.Bes


1 Answers

If your intention is to encode and decode Morse messages with any tool then something like this will do :

#!/usr/local/bin/python3
import re

alphabet = { 'A':'.-', 'B':'-...', 'C':'-.-.', 'D':'-..', 'E':'.', 'F':'..-.', 'G':'--.', 'H':'....', 'I':'..', 'J':'.---', 'K':'-.-', 'L':'.-..', 'M':'--', 'N':'-.', 'O':'---', 'P':'.--.', 'Q':'--.-', 'R':'.-.', 'S':'...', 'T':'-', 'U':'..-', 'V':'...-', 'W':'.--', 'X':'-..-', 'Y':'-.--', 'Z':'--..', '1':'.----', '2':'..---', '3':'...--', '4':'....-', '5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.', '0':'-----', ', ':'--..--', '.':'.-.-.-', '?':'..--..', '/':'-..-.', '-':'-....-', '(':'-.--.', ')':'-.--.-',' ':'  '} 

def encode(message): 
    return "".join([ ( alphabet[letter.upper()] + ' ' ) if letter != ' ' else '  ' for letter in message])

def decode(message):
    return "".join([ list(alphabet.keys())[list(alphabet.values()).index(item if item != '|' else '  ')] for item in re.sub(r' {2,}', ' | ',message).split(' ')])

print(encode('THIS IS FINE'))
print(decode('- .... .. ...   .. ...   ..-. .. -. .'))

Hope it helps too.

like image 94
Matias Barrios Avatar answered Jun 24 '26 14:06

Matias Barrios