The cut command is used to used to display selected columns or fields from each line of a file.
It will be most useful when we are working with shell scripting programs.
We are taking /etc/passwd file for doing some particular tasks with cut command. /etc/passwd file stores the userid details.
To display characters from each line:
Cut command can take out the characters in a line based on their position. We can use “-c” option for this,
we want to display 3rd and 4th characters of /etc/passwd file.
We can use comma separator for giving multiple character display. Sample command and output is,
We want to display character from 10 to 20 from file:
To print the range of characters of a line in a file,
To Display first 10 character of a /etc/passwd:
To Display characters from 10th characters onwards:
To display fields based on delimiters:
For separating the columns based on delimiters we can use option “-d” with cut command.
We want to display 3rd field from each line of file with delimiter as “:”
Field numbers in a file are counted from 0 onwards. So 3rd field is generally referred as “-f2” option.
Sample command output is given below,
Verify the field using cat /etc/passwd
Display fields from 1 to 4 from file:
Display first 5 fields of a file with delimiter as “:”:-
To display piece of any command output:
Cut command can take input from another command output rather than a file itself. Below given an example of “who am I” command output is passed to cut command as input and seeing the first field of it.
Let’s look at the command output in general,
Now let’s cut the first field of this command output based on ‘ ’ as delimiter.