Skip to content

Instantly share code, notes, and snippets.

@alanhoyle
Last active June 25, 2024 16:37
Show Gist options
  • Save alanhoyle/7ec6bd445a790b62567d8b1ff6941c66 to your computer and use it in GitHub Desktop.
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
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
}
@alanhoyle
Copy link
Author

@alanhoyle
Copy link
Author

TODO detect if first parameter is an integer. If it is, use that as the default number of header lines to skip.

@alanhoyle
Copy link
Author

TODO is DONE

@alanhoyle
Copy link
Author

update:

  • add -h | --help options.
  • reformat usage

@alanhoyle
Copy link
Author

alanhoyle commented Nov 7, 2023

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