cut
is a useful command you can pipe stuff to, that helps you cut out parts of the input. You can also pass it a file.
On a delimiter
You can split input on a character using the delimiter
option -d
. Use it alongside the fields
option -f
, e.g. to print the first part of jwt token
Jwt tokens have 3 parts, separated by .
. Here’s the first part of the token shown on jwt.io
echo "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" \
| cut -d "." -f1 \
| base64 -d
{"alg":"HS256","typ":"JWT"}
Range of chars
Cut a range of chars using -c <from>-<to>
echo woot | cut -c 1-2
wo
From char N to the end
echo "one\ntwo\nthree" | cut -c 2-
ne
wo
hree
N chars from the beginning
echo "one\ntwo\nthree" | cut -c -2
on
tw
th
Remove the last char
Combined with rev
, that reverses a line, you can easily remove the last char using cut.
echo "oneX\ntwoY\nthreeZ" | rev | cut -c 2- | rev
one
two
three
Complement
The gnu cut command also accepts a --complement
option, that does the opposite.
If you installed coreutils
using homebrew
, the gnu equivalents of your commands can be found in
/usr/local/opt/coreutils/bin/
brew info coreutils
shows that
Commands also provided by macOS and the commands dir, dircolors, vdir have been installed with the prefix “g”
Use it e.g. as an easy way to remove columns you’re not interested in
gcut -d":" -f2,6,7 --complement /etc/passwd
...
root:0:0:System Administrator
daemon:1:1:System Services
...
Edits:
- [2024-10-09 ons] Fixed broken url