简体   繁体   English

如何在Linux Shell脚本中将内容打印到控制台的最右侧

[英]How to print something to the right-most of the console in Linux shell script

Say I want to search for "ERROR" within a bunch of log files. 假设我要在一堆日志文件中搜索“ ERROR”。

I want to print one line for every file that contains "ERROR". 我想为每个包含“ ERROR”的文件打印一行。

In each line, I want to print the log file path on the left-most edge while the number of "ERROR" on the right-most edge. 在每一行中,我想在最左边打印日志文件路径,而在最右边打印“错误”数。

I tried using: 我尝试使用:

printf "%-50s %d" $filePath $errorNumber

...but it's not perfect, since the black console can vary greatly, and the file path sometimes can be quite long. ...但这并不完美,因为黑色控制台的差异很大,有时文件路径可能会很长。

Just for the pleasure of the eyes, but I am simply incapable of doing so. 只是为了让眼睛愉悦,但我根本无能为力。 Can anyone help me to solve this problem? 谁能帮我解决这个问题?

Using bash and printf : 使用bashprintf

printf "%-$(( COLUMNS - ${#errorNumber} ))s%s" \
       "$filePath" "$errorNumber"

How it works: 这个怎么运作:

  1. $COLUMNS is the shell's terminal width. $COLUMNS是外壳的端子宽度。

  2. printf does left alignment by putting a - after the % . printf通过在%后面加上-进行左对齐。 So printf "%-25s%s\\n" foo bar prints " foo ", then 22 spaces, then " bar ". 因此, printf "%-25s%s\\n" foo bar打印“ foo ”,然后是22个空格,然后是“ bar ”。

  3. bash uses the # as a parameter length variable prefix, so if x=foo , then ${#x} is 3 . bash使用#作为参数长度变量前缀,因此,如果x=foo ,则${#x}3


Fancy version, suppose the two variables are longer than will fit in one column; 花式版本,假设两个变量的长度大于一栏的长度 if so print them on as many lines as are needed: 如果是这样,请根据需要在尽可能多的行上进行打印:

printf "%-$(( COLUMNS * ( 1 + ( ${#filePath} + ${#errorNumber} ) / COLUMNS ) \
          - ${#errorNumber} ))s%s"   "$filePath" "$errorNumber"

Generalized to a function. 泛化为一个函数。 Syntax is printfLR foo bar , or printfLR < file : 语法是printfLR foo barprintfLR < file

printfLR() { if [ "$1" ] ; then echo "$@" ; else cat ; fi |
             while read l r ; do
                 printf "%-$(( ( 1 + ( ${#l} + ${#r} ) / COLUMNS ) \
                              * COLUMNS - ${#r} ))s%s"   "$l" "$r"
             done ;  }

Test with: 测试:

# command line args
printfLR foo bar
# stdin
fortune | tr -s ' \t' '\n\n' | paste - - | printfLR

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM