的hexdump都表明,在.[16D
點實際上是一個轉義字符,\x1b
。
Esc[
nD
是ANSI escape code刪除n
個字符。所以Esc[16D
告訴終端刪除16個字符,這說明了cat
輸出。
有多種方法可以使用Bash命令(例如使用sed
,如Anubhava的答案)或Python來從文件中刪除ANSI轉義代碼。
然而,在這樣的情況下,它可能是更好的通過終端模擬器來運行該文件來解釋任何現有的編輯控制序列的文件,這樣你就應用了這些編輯序列後,他們得到的結果文件的作者的意圖。
在Python中執行該操作的一種方法是使用pyte,這是一個實現簡單的VTXXX兼容終端仿真器的Python模塊。您可以使用pip
輕鬆進行安裝,以下是readthedocs上的文檔。
下面是一個簡單的演示程序,用於解釋問題中給出的數據。它是爲Python 2編寫的,但很容易適應Python 3.支持Unicode,它的標準Stream類需要Unicode字符串,但本例使用ByteStream,所以我可以將它傳遞給普通字節字符串。
#!/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)
輸出輸出
HELLO
十六進制轉儲
00000000 48 45 4c 4c 4f 0a |HELLO.|
你試過string.printable嗎? – therealprashant
我想知道爲什麼Python標籤.... – 0xc0de
在大多數* nix系統上,當然在任何GNU系統上,應該有一個[strings](http://linux.die.net/man/1/strings)命令。 –