Last active
June 25, 2024 16:37
-
-
Save alanhoyle/7ec6bd445a790b62567d8b1ff6941c66 to your computer and use it in GitHub Desktop.
body (): a bash function that prints the first few lines of STDIN (1 line default) and then runs a command on the remaining 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
body() { | |
local HEADER_LINES=1 | |
local COMMAND="sort" | |
if [ -t 0 ]; then | |
>&2 echo "ERROR: body requires piped input!" | |
>&2 echo "" | |
fi | |
if [[ -t 0 || "$1" == "-h" || "$1" == "--help" ]] ; then | |
>&2 echo "body: prints the header from a STDIN and sends the 'body' to another command for" | |
>&2 echo " additional processing. Useful for sort/grep when you want to keep headers." | |
>&2 echo "" | |
>&2 echo "USAGE: COMMAND | body [ N ] [ COMMAND_TO_PROCESS_OUTPUT ]" | |
>&2 echo " if the first parameter N is a whole number, it prints that number of lines" | |
>&2 echo " before proceeding [ default: skip $HEADER_LINES ]" | |
>&2 echo " if the [ COMMAND_TO PROCESS_OUTPUT ] is omitted, '$COMMAND' is used" | |
>&2 echo "" | |
>&2 echo "EXAMPLES:" | |
>&2 echo " Sort a file, but maintain a one-line header:" | |
>&2 echo " cat file_with_one_line_header.txt | body" | |
>&2 echo " Sort a file in reverse, but keep the top two lines of header in place:" | |
>&2 echo " cat file_with_two_line_header.txt | body 2 sort -r" | |
if [[ -t 0 ]] ; then | |
return 1 | |
else | |
return 0 | |
fi | |
fi | |
local re='^[0-9]+$' | |
if [[ $1 =~ $re ]] ; then | |
HEADER_LINES=$1 | |
shift | |
# >&2 echo "skipping $HEADER_LINES" | |
fi | |
local THIS_COMMAND=$@ | |
if [ -z "$THIS_COMMAND" ] ; then | |
>&2 echo "body: running $COMMAND by default" | |
fi | |
for line in $(eval echo "{1..$HEADER_LINES}") | |
do | |
IFS= read -r header | |
printf '%s\n' "$header" | |
done | |
if [ -z "$THIS_COMMAND" ] ; then | |
( $COMMAND ) | |
else | |
"$@" | |
fi | |
} |
TODO detect if first parameter is an integer. If it is, use that as the default number of header lines to skip.
TODO is DONE
update:
- add
-h | --help
options. - reformat usage
update: proper return codes for --help
vs no STDIN.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by https://unix.stackexchange.com/questions/11856/sort-but-keep-header-line-at-the-top