Skip to content

Instantly share code, notes, and snippets.

@NigelThorne
Last active Mar 1, 2022
Embed
What would you like to do?
Col returns the specified columns from each line in stdin
#!/usr/bin/bash
# Usage: col x x x
# where x is a column number or + to mean all following columns
#
# example: ls -al | col 6 7 9
# example: ls -al | col 2 7 +
# example: ls -al | col -1
# Here is a fun use... interleave lines from logs from several containers in timestamp order
# docker-compose logs --tail='all' -t | col 3 1 + | sort | col 2 +
column () {
local args=("awk '{ ")
local last_index=0
if (( $1 < 0 ))
then
args+=("printf \$(NF+1$1);")
last_index="NF+1$1"
else
args+=("printf \$$1;")
last_index=$1
fi
while [[ ! -z "$2" ]]
do
args+=('printf " ";')
shift
if [ ! $1 = "+" ]; then
if (( $1 < 0 ))
then
args+=("printf \$(NF+1$1);")
last_index="NF+1$1"
else
args+=("printf \$$1;")
last_index=$1
fi
else
args+=('for(i='$last_index'+1;i<=NF;++i){printf " ";printf $i;}')
fi
done
args+=("; print \"\"}'")
eval "${args[@]}"
#echo "${args[@]}"
}
column $*
@NigelThorne
Copy link
Author

NigelThorne commented Mar 1, 2022

negative index numbers count from the back of the line.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment