Program to transform a string in hexadecimal?
Question: 
    #!/usr/bin/python3
    
    # -*- coding: utf-8 -*-
    
    import os
    import sys
    
    try:
        string=sys.argv[1]
        cmd = "echo -n "+string+" | xxd -ps | sed 's/[[:xdigit:]]\{2\}/\\\\x&/g'"
        os.system(cmd)
    except IndexError:
        print("\nInforme a string!\n")
    

I found this code on Internet. I tried hard to understand what it does. Could
someone explain?

    
    
    string=sys.argv[1]
    cmd = "echo -n "+string+" | xxd -ps | sed 's/[[:xdigit:]]\{2\}/\\\\x&/g'"
    

The two lines above are like magic to me.


Answer: For the line:

    
    
    cmd = "echo -n "+string+" | xxd -ps | sed 's/[[:xdigit:]]\{2\}/\\\\x&/g'"
    

  * `echo` sends the text to the standard output,
  * `|` pipes that output to `xxd`, which translates binary to hexadecimal (think hex editors); the `-ps` flag, according to the `xxd` man page:

>
>        -p | -ps | -postscript | -plain
>               output  in  postscript  continuous  hexdump style. Also known
> as
>               plain hexdump style.
>  

  * `sed` is the stream editor command - there are literally books on this. Basically here, the piped hexdecimal output from the `xxd -ps` command has this replacement regex performed, broken down here:
    
        sed 's/          # Start find
    [[:xdigit]]\{2\} # Match two or more hexadecimal characters 
                     # ([[:xdigit:]] is POSIX-compliant representation 
                     # of hexadecimal character)
    /                # End find, start replace
    \\\\x&           # Lots of escaping backslashes - as \x&; the ampersand
                     # becomes the entire previous match  (the 2 hexadecimal
                     # characters), e.g. '\x8e'
    /g'              # End find, and g means all matches are changed
    

> \xxx Produces or matches a character whose hexadecimal ascii value is xx.
> ([source](https://www.gnu.org/software/sed/manual/html_node/Escapes.html))

  * In a nutshell, the scripts takes an input and translates it to hexadecimal, and then the `sed` command converts them to ascii characters for each double of hexadecimal code characters from the `xxd` input.

