La hexdump mostra che il punto in .[16D
è in realtà un carattere di escape, \x1b
.
Esc[
nD
è un ANSI escape code per eliminare n
caratteri. Quindi, Esc[16D
indica al terminale di eliminare 16 caratteri, il che spiega l'output di cat
.
Esistono vari modi per rimuovere i codici di escape ANSI da un file, utilizzando i comandi di Bash (ad esempio utilizzando sed
, come nella risposta di Anubhava) o Python.
Tuttavia, in casi come questo, potrebbe essere preferibile eseguire il file tramite un emulatore di terminale per interpretare eventuali sequenze di controllo di modifica esistenti nel file, in modo da ottenere il risultato desiderato dall'autore del file dopo aver applicato tali sequenze di modifica.
Un modo per farlo in Python è utilizzare pyte, un modulo Python che implementa un semplice emulatore di terminale VTXXX compatibile. Puoi installarlo facilmente usando pip
, e qui ci sono i suoi documenti su readthedocs.
Ecco un semplice programma dimostrativo che interpreta i dati forniti nella domanda. È scritto per Python 2, ma è facile adattarsi a Python 3. pyte
è compatibile con Unicode e la sua classe Stream standard prevede le stringhe Unicode, ma in questo esempio viene utilizzato un ByteStream, quindi posso passarlo una stringa di byte semplice.
#!/usr/bin/env python
''' pyte VTxxx terminal emulator demo
Interpret a byte string containing text and ANSI/VTxxx control sequences
Code adapted from the demo script in the pyte tutorial at
http://pyte.readthedocs.org/en/latest/tutorial.html#tutorial
Posted to http://stackoverflow.com/a/30571342/4014959
Written by PM 2Ring 2015.06.02
'''
import pyte
#hex dump of data
#00000000 48 45 4c 4c 4f 20 54 48 49 53 20 49 53 20 54 48 |HELLO THIS IS TH|
#00000010 45 20 54 45 53 54 1b 5b 31 36 44 20 20 20 20 20 |E TEST.[16D |
#00000020 20 20 20 20 20 20 20 20 20 20 20 1b 5b 31 36 44 | .[16D|
#00000030 20 20 | |
data = 'HELLO THIS IS THE TEST\x1b[16D \x1b[16D '
#Create a default sized screen that tracks changed lines
screen = pyte.DiffScreen(80, 24)
screen.dirty.clear()
stream = pyte.ByteStream()
stream.attach(screen)
stream.feed(data)
#Get index of last line containing text
last = max(screen.dirty)
#Gather lines, stripping trailing whitespace
lines = [screen.display[i].rstrip() for i in range(last + 1)]
print '\n'.join(lines)
uscita
HELLO
esadecimale discarica di uscita
00000000 48 45 4c 4c 4f 0a |HELLO.|
fonte
2015-06-01 10:37:52
hai provato string.printable? – therealprashant
Mi chiedo perché il tag python .... – 0xc0de
Sulla maggior parte dei sistemi * nix, e certamente su qualsiasi sistema GNU, dovrebbe esserci un comando [stringhe] (http://linux.die.net/man/1/strings) . –