When issuing the docker container ls -la command, the output looks like this:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a67f0c2b1769 busybox "tail -f /dev/null" 26 seconds ago Up 25 seconds recursing_liskov
I'd like to get only the container's name present in the Names column.
My idea was to use bash to reverse the columns in the command output so as to get the Names column in first position and cut the name of container.
This is what I tried:
sudo docker container ls -la | rev |tail -n +2 | tr -s ' ' | cut -d ' ' -f 1
However this does not give the expected result and I get the following error:
rev: stdin: Invalid or incomplete multibyte or wide character
I'm stuck as I don't know how to handle this error. Can it be fixed to obtain the result I expect ? Or is there any other way to obtain my result ?
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 what you are looking for:
$ docker container ls -la --format "{{.Names}}"
recursing_liskov
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
{
"Command": "\"tail -f /dev/null\"",
"CreatedAt": "2022-01-15 23:43:54 +0100 CET",
"ID": "a67f0c2b1769",
"Image": "busybox",
"Labels": "",
"LocalVolumes": "0",
"Mounts": "",
"Names": "recursing_liskov",
"Networks": "bridge",
"Ports": "",
"RunningFor": "20 minutes ago",
"Size": "0B (virtual 1.24MB)",
"State": "running",
"Status": "Up 20 minutes"
}
Here is an example just to illustrate using some of the fields:
$ docker container ls -la --format "container {{.Names}} is in state {{.State}} and has ID {{.ID}}"
container recursing_liskov is in state running and has ID a67f0c2b1769
Some random references out of several I used:
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).