-
-
Save NigelThorne/1cdde523d94e9d591d72e12544892a04 to your computer and use it in GitHub Desktop.
Col returns the specified columns from each line in stdin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 $* |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
negative index numbers count from the back of the line.