Cut

cut is a linux command line tool that allows us to remove a section from each line provided, whether that is a file or the output of another command. Lets see a simple run of the cut command:

echo "Hello there world! What a wonderful day!" | cut -c 1-15
Hello there wor

We piped our echo statement into cut and gave it the -c flag to indicate we wanted to grab a certain section of characters including spaces from each line provided. In this case we only have one line of text so we grabbed characters 1-15 from it. We can also just cut characters from a file:

cut -c 1-8 /etc/shells
# Pathna
# See sh

/bin/sh
/bin/bas
/usr/bin
/usr/bin
/bin/fis

Here we grabbed the first 8 characters of each line of our /etc/shells file. We don't have to give cut an exact range of characters either. Say we wanted to grab everything after the first 6 characters of our shells file:

cut -c 6- /etc/shells
hnames of valid login shells.
 shells(5) for details.

sh
bash
bin/git-shell
bin/fish
fish

This would give us a list of our installed shells.

Delimiters

cut can do more than just grab a range of characters for us though. The -d flag allows us to provide a delimiter to tell cut what each of the fields we want to work with are separted by. Lets see an example of that:

echo "Hello there world! What a wonderful day!" | cut -d ' ' -f3
world!

We just told cut that we want to separate our text into fields based on an empty space. We then told cut that we wanted the third field (-f3). Lets see a real world example of when this would be used:

cut -d ':' -f1 /etc/passwd
root
bin
daemon
mail
ftp
http
nobody
dbus
systemd-journal-remote
systemd-network
systemd-resolve
systemd-timesync
systemd-coredump
uuidd
avahi
colord
dhcpcd
git
lightdm
polkitd
epost
brltty
dnsmasq
nvidia-persistenced
rtkit
usbmux
systemd-oom

We told cut to look in /etc/passwd and use the delimiter : to print us the first field of each line. This provided us with the users on our system.

This page was last updated: 2024-11-06 Wed 14:11. Source