Home > Mobile >  Reverse stdout in bash
Reverse stdout in bash

Time:11-13

i have a question how come is to treat stdout as string in bash to reverse the output. 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.

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

CodePudding user response:

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.

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. You can easily get a list of all keys available with something like:

docker container ls -la --format "{{json .}} | jq

Some random references:

CodePudding user response:

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. 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).

  • Related