简体   繁体   English

在 bash 中反转标准输出

[英]Reverse stdout in bash

i have a question how come is to treat stdout as string in bash to reverse the output.我有一个问题,如何将标准输出视为 bash 中的字符串来反转输出。 My goal is to get reverse columns in command: docker container ls -la to get column NAMES as first one to cut the name of container.我的目标是在命令中获取反向列: docker container ls -la以获取列名称作为第一个剪切容器名称的列。

sudo docker container ls -la | rev |tail -n +2 | tr -s ' ' | cut -d ' ' -f 1

However i am getting errors like:但是我收到如下错误:

rev: stdin: Invalid or incomplete multibyte or wide character

How to handle it?如何处理? I would like to obtain column NAMES (which is the last) as first one using command cut我想使用命令cut获取列 NAMES(这是最后一个)作为第一个

Rather than playing around with a default output, just print exactly what you are looking for from start.与其玩弄默认输出,不如从一开始就准确打印您要查找的内容。 Most docker sub-commands accept a --format option which will take a go template expression to specify what you exactly want.大多数 docker 子命令都接受--format选项,该选项将采用 go 模板表达式来指定您确切想要的内容。

In your case, I believe the following command should give exactly what you are looking for:在您的情况下,我相信以下命令应该提供您正在寻找的内容:

docker container ls -la --format "{{.Names}}"

Of course, you can add more columns if you wish, in whatever order best suits your needs.当然,如果您愿意,您可以按最适合您需要的任何顺序添加更多列。

The first reference I could find looking over the web: https://devcoops.com/filter-output-of-docker-image-ls/我在网上找到的第一个参考资料: https : //devcoops.com/filter-output-of-docker-image-ls/

I am not sure if I understood your question, but if you just want to rearrange the order of the columns, you can use awk and its printf function.我不确定我是否理解您的问题,但如果您只想重新排列列的顺序,您可以使用awk及其printf函数。 It's not the most elegant way, but depending on your use case, it might work for you.这不是最优雅的方式,但根据您的用例,它可能适合您。

For instance, you can use the following for a two columns output command:例如,您可以将以下内容用于两列输出命令:

cmd | awk '{printf ("%s\t%s\n", $1, $2)}'

In the same fashion, you could do:以同样的方式,你可以这样做:

docker container ls -la | awk '{printf ("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", $8, $1, $2, $3, $4, $5, $6, $7)}'

As I said, this can be considered a dirty workaround but I am not sure what your use case demands.正如我所说,这可以被视为一种肮脏的解决方法,但我不确定您的用例需要什么。 Note that the first row with the columns name won't be as pretty as it is by default.请注意,带有列名称的第一行不会像默认情况下那样漂亮。 You can fix that giving each of the elements a (max) width ( %5s sets a width of 5).您可以修复为每个元素提供(最大)宽度( %5s将宽度设置为 5)的问题。

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

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