仅显示命令输出的最近一行 [英] Displaying only single most recent line of a command's output

查看:72
本文介绍了仅显示命令输出的最近一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在一行中打印类似rm -rv *的命令输出?我认为它需要\r,但我不知道如何.

How can I print a command output like one from rm -rv * in a single line ? I think it would need \r but I can't figure out how.

我需要这样的东西:

发件人:

removed /path/file1
removed /path/file2
removed /path/file3

收件人:Line 1 : removed /path/file1

然后:Line 1 : removed /path/file2

然后:Line 1 : removed /path/file3

EDIT :我可能被误解了,我希望整个过程都在同一行中进行打印,随着命令输出另一行而改变(例如removed /path/file123)

EDIT : I may have been misunderstood, I want to have the whole process beeing printing in a single same line, changing as the command outputs an another line (like removed /path/file123)

EDIT2 :有时输出太长而无法在线显示(很长的路径).我也需要考虑到该问题的东西:
/very/very/very/long/path/to/a/very/very/very/far/file/with-a-very-very-very-long-name1
/very/very/very/long/path/to/a/very/very/very/far/file/with-a-very-very-very-long-name2
/very/very/very/long/path/to/a/very/very/very/far/file/with-a-very-very-very-long-name3

EDIT2 : The output is sometimes too long to be display in on line (very long path). I would need something that considers that problem too :
/very/very/very/long/path/to/a/very/very/very/far/file/with-a-very-very-very-long-name1
/very/very/very/long/path/to/a/very/very/very/far/file/with-a-very-very-very-long-name2
/very/very/very/long/path/to/a/very/very/very/far/file/with-a-very-very-very-long-name3

推荐答案

以下是一个辅助函数:

shopt -s checkwinsize # ensure that COLUMNS is available w/ window size

oneline() {
  local ws
  while IFS= read -r line; do
    if (( ${#line} >= COLUMNS )); then
      # Moving cursor back to the front of the line so user input doesn't force wrapping
      printf '\r%s\r' "${line:0:$COLUMNS}"
    else
      ws=$(( COLUMNS - ${#line} ))
      # by writing each line twice, we move the cursor back to position
      # thus: LF, content, whitespace, LF, content
      printf '\r%s%*s\r%s' "$line" "$ws" " " "$line"
    fi
  done
  echo
}

用途如下:

rm -rv -- * 2>&1 | oneline


为了更加安全地进行测试,可以使用:


To test this a bit more safely, one might use:

for f in 'first line' 'second line' '3rd line'; do echo "$f"; sleep 1; done | oneline

...您将看到该测试显示first line一秒钟,然后显示second line一秒钟,然后显示3rd line一秒钟.

...you'll see that that test displays first line for a second, then second line for a second, then 3rd line for a second.

这篇关于仅显示命令输出的最近一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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