Bash 中的退格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4644350/
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
Backspacing in Bash
提问by Kyle Hotchkiss
How do you backspace the line you just wrote with bash and put a new one over its spot? I know it's possible, Aptitude (apt-get) use it for some of the updating stuff and it looks great.
你如何退格你刚刚用 bash 写的行并在它的位置上放一个新的?我知道这是可能的,Aptitude (apt-get) 将它用于一些更新内容,它看起来很棒。
回答by Paused until further notice.
Try this:
尝试这个:
$ printf "12345678\rABC\n"
ABC45678
As you can see, outputting a carriage return moves the cursor to the beginning of the same line.
如您所见,输出回车会将光标移动到同一行的开头。
You can clear the line like this:
您可以像这样清除该行:
$ printf "12345678\r$(tput el)ABC\n"
ABC
Using tputgives you a portable way to send control characters to the terminal. See man 5 terminfofor a list of control codes. Typically, you'll want to save the sequence in a variable so you won't need to call an external utility repeatedly:
使用tput为您提供了一种向终端发送控制字符的便携方式。有关man 5 terminfo控制代码列表,请参见。通常,您需要将序列保存在一个变量中,这样您就不需要重复调用外部实用程序:
$ clear_eol=$(tput el)
$ printf "12345678\r${clear_eol}ABC\n"
ABC
回答by JimR
It's not really clear to me what you want, but, depending on your terminal settings you can print ^H (control H) to the screen and that will back the cursor up one position.
我不太清楚您想要什么,但是,根据您的终端设置,您可以将 ^H(控制 H)打印到屏幕上,这会将光标移回一个位置。
Also note that some terminals have the ability to move the cursor to the beginning of the line, in which case you'd move to the beginning of the line, print enough spaces to overwrite the entire line (Usually available from $COLUMNS) and then print any message or whatever.
另请注意,某些终端可以将光标移动到行首,在这种情况下,您将移动到行首,打印足够的空格以覆盖整行(通常可从 $COLUMNS 获得),然后打印任何消息或其他任何内容。
If you clarify exactly what you want and I can answer you I'll update my answer.
如果您明确说明您想要什么并且我可以回答您,我会更新我的答案。
回答by carlo
Here's an example using the find command & a while-read loop to continually print full file paths to stdout on a single line only:
这是一个使用 find 命令和一个 while-read 循环的示例,它仅在一行上连续打印到 stdout 的完整文件路径:
command find -x / -type f -print0 2>/dev/null | while read -d $'##代码##' filename; do
let i+=1
filename="${filename//[[:cntrl:]]/}" # remove control characters such as \n, \r, ...
if [[ ${#filename} -lt 85 ]]; then
printf "\r\e[0K\e[1;32m%s\e[0m %s" "${i}" "${filename}"
else
printf "\r\e[0K\e[1;32m%s\e[0m %s" "${i}" "${filename:0:40}.....${filename: -40}"
fi
done; echo

