Hello, everyone In this Article we are going to learn how we can use the cut command in Linux with examples in a very simple and easy step-by-step approach.
Cut command in linux
Suppose we have a file and from that file, we want to cut every 5 characters and paste on the screen or we want to cut the field from the file we want to get username and userid on the screen only and whole output is no more in this scenario we can use the cut command.
cut command use to cut any record using characters and fields from any file / from any command output.
Before Jumping on the command we should know the syntax of the cut command
cut [ options ] [ filename ]
Options
-c => cut by characters of every row
-d => define the delimiter symbol it can be anything ( , “” space ) etc.
-f => cut by fields => we cannot use this option without defining the delimiter symbol
How to display the First character
To display only the first character of the File then we can execute the below command
# cut -c1 /etc/passwd
How to display specific character
To display only the First and the third character of the File then we can execute the below command
# cut -c1,3 /etc/passwd
How to display the range of character
To display the range of character from 1-5 of the File then we can execute the below command
# cut -c1-5 /etc/passwd
How to display the range from bottom of the File
To display the last line from the file and range of the fields from 1-6 then we can execute the below command
tail -n1 /etc/passwd | cut -c1-6
How to display the First Field
To display the first field then we can execute below command
# cut -d':' -f1 /etc/passwd
How to display number of fields
To display the third and sixth field then we can execute below command
# cut -d':' -f1,3,6 /etc/passwd
How to display specific field from bottom of the file
To display the first and seventh field from the bottom of the file then we can execute the below command
# tail -n5 /etc/passwd | cut -d: -f1,7
How to display the range of the field
To display the range from 1-4 separated by ( : ) delimiter from the bottom of the file then we can execute the below command
# tail -n5 /etc/passwd | cut -d: -f1-4
How to display the Field with spaces between them
To display the fields separated by the space delimiter then we can add ( ‘ ‘) symbol with spaces between them
# cat /var/log/secure | tail -n5 | cut -d ' ' -f1-4 > /tmp/info
Conclusion
If you want to learn Linux in the most simple language then please click on this link.
If you want to see the man page of cut command online then click on this link
This is the complete knowledge of how we can use the cut command in the Linux kernel if you have any doubts please feel free to comment below. Please don’t forget to join our email subscription to get the latest updates on the DevOps Articles.