我可以以编程方式“刻录"吗?使用 unix utils 将 ANSI 控制代码写入文件? [英] Can I programmatically "burn in" ANSI control codes to a file using unix utils?

查看:23
本文介绍了我可以以编程方式“刻录"吗?使用 unix utils 将 ANSI 控制代码写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:我使用 script 开始录制,并尝试键入 echo test 但省略了 o,所以我退格以更正它.

Example: I start recording with script, and try to type echo test but omit the o, so I backspace to correct it.

当我 cat typescript 一切看起来正常,因为代码被解释,但如果我使用 lessvim 我看到 ech test^H^[[K^H^[[K^H^[[K^H^[[K^H^[[Ko test^M

When I cat typescript everything looks normal, since the codes are interpreted, but if I use less or vim I see ech test^H^[[K^H^[[K^H^[[K^H^[[K^H^[[Ko test^M

我完全理解这是什么以及为什么会发生,但是有什么方法可以刻录"代码并在文件中查看结果?我的笨拙方法是 cat 文件,然后将文本复制/粘贴到终端之外,但肯定 cat、sed、awk 或其他东西的某种组合可以让我更轻松地到达那里?

I fully understand what this is and why it's happening, but is there any way to "burn in" the codes and just see the result in a file? My kludgy method is to cat the file, then copy/paste the text out of the terminal, but surely some combination of cat, sed, awk, or something else can get me there more easily?

推荐答案

要显示包含 ANSI 序列的文件,

To display a file that contains ANSI sequences,

less -r typescript

或者,

less -R typescript

要从文件中删除 ANSI 和退格序列,创建一个干净的 newfile,请尝试:

To remove ANSI and backspace sequences from a file, creating a clean newfile, try:

sed -r ':again; s/[^x08]x08x1b[K//; t again; s/x1b_[^x1b]*x1b[]//g; s/x1B[[^m]*m//g' typescript >newfile

工作原理

  • -r

    这会打开扩展的正则表达式.(在 BSD 系统上,-r 应替换为 -E.现代版本的 GNU sed 将接受 -r-E.)

    This turns on extended regular expressions. (On BSD systems, -r should be replaced with -E. Modern versions of GNU sed will accept either -r or -E.)

    `:再次;s/[^x08]x08x1b[K//;再来一次

    `:again; s/[^x08]x08x1b[K//; t again

    这会删除任何退格序列.这些是在循环中一次完成的.

    This removes any backspace sequences. These are done one at a time in a loop.

    s/x1b_[^x1b]*x1b[]//g

    作为 xterm 扩展(参见 文档), Esc _ something Esc 什么都不做.此命令删除这些序列.

    As an xterm extension (see documentation), Esc _ something Esc will do nothing. This command removes these sequences.

    s/x1B[[^m]*m//g

    这会删除设置颜色等的剩余 ANSI 序列.

    This removes the remaining ANSI sequences which set colors, etc.

    这涵盖了我通常遇到的所有控制序列.有各种各样的扩展控制序列,如果您的输出中有一些我没有看到,则可能需要扩展代码.

    This covers all the control sequences that I normally run into. There are a wide variety of extended control sequences and, if your output has some that I haven't seen, the code may need to be extended.

    在 BSD 或 POSIX 系统上,必须使用 -e 选项而不是分号将各个命令链接在一起.因此,尝试:

    On a BSD or POSIX system, individual commands have to be chained together with -e options instead of semicolons. Thus, try:

    sed -e ':again' -e 's/[^x08]x08x1b[K//' -e 't again' -e 's/x1b_[^x1b]*x1b[]//g' -e 's/x1B[[^m]*m//g'
    

    这篇关于我可以以编程方式“刻录"吗?使用 unix utils 将 ANSI 控制代码写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆