Skip to content

Instantly share code, notes, and snippets.

@NigelThorne
Last active March 1, 2022 00:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NigelThorne/1cdde523d94e9d591d72e12544892a04 to your computer and use it in GitHub Desktop.
Save NigelThorne/1cdde523d94e9d591d72e12544892a04 to your computer and use it in GitHub Desktop.
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

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