Cracking IT Interview


cut (Text Cutting)


This is a command for cutting some text from each line (row-wise cut) of files and writing the result to standard output. This command best applies when we want only an information of our interest from a file and has to be embedded into shell scripts or in other program codes. 


Basically it is used to cut as:


  • Character
  • Byte 
  • Field






Character-wise cut in file:


Use "-c" option with cut command:  


  • cut -c 1 filename  - cut 1st character from filename


  • cut -c 1,3 filename  - cut 1st and 3rd character from filename


  • cut -c -3 filename  - cut from beginning to 3rd i.e 1st, 2nd, 3rd character from filename 


  • cut -c 3- filename  - cut from 3rd to end of line


  • cut -c 3-5 filename  - cut from 3rd to 5th character of file 



Example:


$cat language
C|primary|4|3
C++|primary|3|3
JAVA|secondary|2|2
SQL|secondary|3|2
UNIX|primary|4|4
$

​$cut -c 1 language
C
C
J
S
U

$

$cut -c 1,3 language
Cp
C+
JV
SL
UI
$

​$cut -c -3 language
C|p
C++
JAV
SQL
UNI
$
$cut -c 3- language
primary|4|3
+|primary|3|3
VA|secondary|2|2
L|secondary|3|2
IX|primary|4|4
$

$cut -c 3-5 language
pri
+|p
VA|
L|s
IX|
$



Byte-wise cut in file:


The principle behind "-b" option is similar to described previously. We know that a single character has size of 1 byte and therefore result after executing previous commands with "-b" option will be exactly the same.








Field-wise cut in file:


Use "-f" option for giving field number and "-d" option for delimiter symbol.


  • cut -d"|" -f 2 filename  - cut second field separated by "|" delimiter 


  • cut -d"|" -f 1,3 filename  - cut 1st and 3rd field from filename 


  • cut -d"|" -f -3 filename  - cut from beginning to 3rd field in filename 


  • cut -d"|" -f 3- filename  - cut from 3rd field to end of line in file 


  • cut -d"|" -f 2-4 filename  - cut from 2nd to 4th field in file 


Example:


$cat language
C|primary|4|3
C++|primary|3|3
JAVA|secondary|2|2
SQL|secondary|3|2
UNIX|primary|4|4
$

​$cut -d"|" -f 2 language
primary
primary
secondary
secondary
primary
$

​$cut -d"|" -f 1,3 language
C|4
C++|3
JAVA|2
SQL|3
UNIX|4
$
$cut -d"|" -f -3 language
C|primary|4
C++|primary|3
JAVA|secondary|2
SQL|secondary|3
UNIX|primary|4
$
$cut -d"|" -f 3- language
4|3
3|3
2|2
3|2
4|4
$
$cut -d"|" -f 2-4 language
primary|4|3
primary|3|3
secondary|2|2
secondary|3|2
primary|4|4
$



NEXT ->