linux - 清除 Linux 终端模拟器中的最后两行(以及更多)打印行

标签 linux terminal console-application

我曾经看到一个控制台应用程序,它使用多个进度条可视化多个下载的进度,每个进度条都在自己的行上。我很好奇如何做到这一点,但我只找到了部分解决方案。它们在这里:

一个进度条很简单

使用 "carriage return" 可以轻松清除一行从而可视化一个进度条,正如所讨论的 e.g. in this question 。易于使用,也有很多辅助库。

“使用 ncurses”

每个人都说“使用 ncurses”。但据我所知,每个 ncurses 程序都必须以 initscr() 调用开始,这确实会清除整个屏幕。您的提示消失了,您的终端历史记录也消失了。这不是我想要的。

使用 ncurses 中的 terminfo

使用 terminfo 中的 scedrc 功能,如该 Bash 脚本所示(该脚本取自 this question):

tput sc; while [ true ]; do tput ed; echo -e "$SECONDS\n$SECONDS\n$SECONDS"; sleep 1; tput rc; done

这有效,但仅在 xterm 中有效。我的 urxvt 术语忽略它,与例如相同终止符

那么还有什么其他选择?

最佳答案

正如用户@Marged正确指出的那样,ANSI escape sequences就是答案。

这是适合我的 C 代码。关键是第 19 行,它打印删除最后两行的 ANSI 序列(行数是任意的,在序列中说明):

#include <stdio.h>
#include <unistd.h>

void progressBar(int done, int total) {
    int i;
    printf("[");
    for (i=0; i<total; ++i) {
        printf((done < i) ? " " : "=");
    }
    printf("]\n");
}

int main() {
    int i;
    for (i=0; i<5; ++i) {
        progressBar(i, 4);
        progressBar(2*i, 8);
        if (i != 4) {
            printf("\033[2A");  // This erases last two lines!
            sleep(1);
        }
    }
    return 0;
}

关于linux - 清除 Linux 终端模拟器中的最后两行(以及更多)打印行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50201165/

相关文章:

c# - SetConsoleActiveScreenBuffer 不显示屏幕缓冲区

linux - Azure 开发运营 : What's the difference between the "Hosted Linux Preview" and "Hosted Ubuntu 1604" agent pools?

linux - 管道命令使标准输入中断

ruby - 在 ubuntu 中安装 ruby​​-bundler 和更新 header 的困难

python - 在 Python 中捕获终端输出

ColdFusion 'Run As Service' 与 'Run in Console'

linux - 检查程序是否存在

linux -/usr/bin/find : Argument list too long, 在尝试删除 164850 个文件时得到这个

linux - 通过 dbus 将 Ctrl-L 发送到终端仿真器

linux - 如何在没有./的情况下执行Linux控制台应用程序