如何获取光标在终端中的位置? [英] How can I get position of cursor in terminal?

查看:730
本文介绍了如何获取光标在终端中的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以使用 tput sc 保存位置,但是如何读取它的位置到变量?我需要行数。

I know I may save position using tput sc, but how can I read it's position to the variable? I need the number of row. I don't want to use curses/ncurses.

推荐答案

在ANSI兼容终端上,打印序列 ESC [6n 会将光标位置报告给应用程序(如在键盘上键入) ESC [n; mR ,其中 n 是行, m 是列。

At ANSI compatible terminals, printing the sequence ESC[6n will report the cursor position to the application as (as though typed at the keyboard) ESC[n;mR, where n is the row and m is the column.

~$ echo -e "\033[6n"

已编辑:

您应确保您正在阅读键盘输入。终端将键入只是 ESC [n; mR 序列(无ENTER键)。在 bash 中,您可以使用类似于:

You should make sure you are reading the keyboard input. The terminal will "type" just the ESC[n;mR sequence (no ENTER key). In bash you can use something like:

echo -ne "\033[6n"            # ask the terminal for the position
read -s -d\[ garbage          # discard the first part of the response
read -s -d R foo              # store the position in bash variable 'foo'
echo -n "Current position: "
echo "$foo"                   # print the position

说明: -d R (delimiter)参数将使 char R 而不是默认记录分隔符( ENTER )。这将在 $ foo 中存储 ESC [n; m 。剪切使用 [作为分隔符,并选择第二个字段,让 n; m (row; column)。

Explanation: the -d R (delimiter) argument will make read stop at the char R instead of the default record delimiter (ENTER). This will store ESC[n;m in $foo. The cut is using [ as delimiter and picking the second field, letting n;m (row;column).

我不知道其他shell。你最好的镜头是Perl,Python或某事的一些oneliner。在Perl中,您可以从以下(未测试的)片段开始:

I don't know about other shells. Your best shot is some oneliner in Perl, Python or something. In Perl you can start with the following (untested) snippet:

~$ perl -e '$/ = "R";' -e 'print "\033[6n";my $x=<STDIN>;my($n, $m)=$x=~m/(\d+)\;(\d+)/;print "Current position: $m, $n\n";'

如果您输入:

~$ echo -e "z033[6n"; cat > foo.txt

按[ENTER]几次,然后按[CRTL] + [D]。然后尝试:

Press [ENTER] a couple times and then [CRTL]+[D]. Then try:

~$ cat -v foo.txt
^[[47;1R

n m 值为47和1.有关详细信息,请参阅维基百科关于ANSI转义代码的文章信息。

The n and m values are 47 and 1. Check the wikipedia article on ANSI escape codes for more information.

在互联网之前,在 BBS ,像我这样的老屁股有很多乐趣与这些代码。

Before the Internet, in the golden days of the BBS, old farts like me had a lot of fun with these codes.

这篇关于如何获取光标在终端中的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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