learn Cut Command in Unix with Simple and Practical Examples:
Unix provides a number of filter commands that can be used for processing flat file databases. These filter commands can be chained together to perform a series of operations with a single command.
A flat file database is a file that contains a table of records, each of which contains fields separated by delimiter characters. In such a database, there is no structural relationship between records, and there is no structure for indexing.
Cut Command in Unix with Examples
The cut command extracts a given number of characters or columns from a file. For cutting a certain number of columns it is important to specify the delimiter. A delimiter specifies how the columns are separated in a text file
Example: Number of spaces, tabs or other special characters.
Syntax:
cut [options] [file]
The cut command supports a number of options for processing different record formats. For fixed width fields, the -c option is used.
$ cut -c 5-10 file1
This command will extract characters 5 to 10 from each line.
For delimiter separated fields, the -d option is used. The default delimiter is the tab character.
$ cut -d “,” -f 2,6 file1
This command will extract the second and sixth field from each line, using the ‘,’ character as the delimiter.
Example:
Assume the contents of the data.txt file is:
Employee_id;Employee_name;Department_name;Salary
10001;Employee1;Electrical;20000
10002; Employee2; Mechanical;30000
10003;Employee3;Electrical;25000
10004; Employee4; Civil;40000
And the following command is run on this file:
$ cut -c 5 data.txt
The output will be:
o 1 2 3 4
If the following command is run on the original file:
$ cut -c 7-15 data.txt
The output will be:
ee_id; Emp Employee1 Employee2 Employee3 Employee4
If the following command is run on the original file:
$ cut -d “,” -f 1-3 data.txt
The output will be:
Employee_id;Employee_name;Department_name 10001;Employee1;Electrical 10002; Employee2; Mechanical 10003;Employee3;Electrical 10004; Employee4; Civil
Conclusion
Two powerful commands for processing the databases are ‘cut’ and ‘paste’. The cut command in Unix is used to extract specified parts of each line in a file, and the paste command is used to insert the contents of one file into another line by line.