« Back to Index

Bash: moreutils examples

View original Gist on GitHub

Tags: #bash #moreutils #shell

examples.bash

# brew install moreutils
# https://joeyh.name/code/moreutils/

# vipe allows you to use vim to inspect data in the middle of a pipeline
$ echo '{"foo": {"bar": 123}}' | vipe --suffix json | jq
{
  "foo": {
    "bar": 123
  }
}

# pee is like tee but for pipes
#
# Each command is run and fed a copy of the standard input.
# The output of all commands is sent to stdout.
#
# NOTE: a copy of the input is not sent to stdout, like tee does
# If that is desired, use pee cat.
#
# In the following example we want the _original_ stdout from cat 
# to be passed over to the wc command, hence we use `pee cat`.
$ seq 5 1 > file
$ cat file | pee cat 'sort -u > sorted' 'sort -R > unsorted' | wc -l
       5
       
# If we didn't use `pee cat` then the example pee pipelines we run
# wouldn't cause any stdout for the `wc` command to receive as stdin.
# 
# We could mimic `pee cat` (although not quite) by having a pipeline
# that uses `xargs` to echo the input, but instead of getting 5 lines 
# of output (from cat'ing the file) we get `5 4 3 2 1` on one line. 
# Hence in the following example I use `wc -w` and not `wc -l`.
$ cat file | pee 'sort -u > sorted' 'sort -R > unsorted' 'xargs' | wc -w
       5