Linux 如何在终端中获取光标的位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8343250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 02:40:03  来源:igfitidea点击:

How can I get position of cursor in terminal?

linuxterminalcursorposition

提问by ciembor

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.

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

回答by Paulo Scardine

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

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

Example:

例子:

~$ echo -e "3[6n"

EDITED:

编辑:

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

您应该确保您正在阅读键盘输入。终端将仅“输入”ESC[n;mR序列(无 ENTER 键)。在bash你可以使用类似的东西:

echo -ne "3[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

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

说明:-d R(delimiter) 参数将read在字符处停止,R而不是默认的记录分隔符 ( ENTER)。这将存储ESC[n;m$foo. 剪切[用作分隔符并选择第二个字段,让n;m(行;列)。

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、Python 或其他语言编写的 oneliner。在 Perl 中,您可以从以下(未经测试的)片段开始:

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

For example, if you enter:

例如,如果您输入:

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

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

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

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

The nand mvalues are 47 and 1. Check the wikipedia article on ANSI escape codesfor more information.

nm值是47和1。检查的ANSI转义码Wikipedia文章以获取更多信息。

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

在没有互联网之前,在BBS的黄金时代,像我这样的老屁都玩这些代码玩得很开心。