cut

remove sections from each line of files

Syntax

cut [OPTION]... [FILE]...

Description

Print selected parts of lines from each FILE to standard output. With no FILE, or when FILE is -, read standard input.

Options

-b, --bytes=LIST
       select only these bytes

-c, --characters=LIST
       select only these characters

-d, --delimiter=DELIM
       use DELIM instead of TAB for field delimiter

-f, --fields=LIST
       select only these fields; also print any line that contains no delimiter character, unless the -s option is specified

-n     with -b: don’t split multibyte characters

--complement
       complement the set of selected bytes, characters or fields

-s, --only-delimited
       do not print lines not containing delimiters

--output-delimiter=STRING
       use STRING as the output delimiter the default is to use the input delimiter

Use one, and only one of -b, -c or -f. Each LIST is made up of one range, or many ranges separated by commas. Selected input is written in the same order that it is read, and is written exactly once. Each range is one of:

       N      N’th byte, character or field, counted from 1

       N-     from N’th byte, character or field, to end of line

       N-M    from N’th to M’th (included) byte, character or field

       -M     from first to M’th (included) byte, character or field

Example 1

Extract username and their login shell from a /etc/passwd file.

[eleiss@eleiss ~]$ cat /etc/passwd  | cut -d":" -f 1,7
root:/bin/bash
bin:/sbin/nologin
daemon:/sbin/nologin
adm:/sbin/nologin
lp:/sbin/nologin
[eleiss@eleiss ~]$

In this example ":" is provided as a delimiter to the cut command. As you may know, a password file in Linux is a seven fields file where every field is separated by ":"

cut command is one the most used commands in shell scripts.

Example 2

Display only file types and permissions of files in the current directory.

[eleiss@eleiss ~]$ ls -l
total 24068
-rw-------. 1 eleiss eleiss    14653 Feb  3  2011 autosave.xmi
drwxr-xr-x. 2 eleiss eleiss     4096 Jun 30 17:33 Desktop
drwxr-xr-x. 2 eleiss eleiss     4096 Apr 25 00:36 Documents
drwxrwxr-x. 3 eleiss eleiss     4096 Sep  4 19:46 empty
drwxr-xr-x. 2 eleiss eleiss     4096 Aug  5  2010 Music
-rw-rw-r--. 1 eleiss eleiss 24539234 Aug 12  2010 out.ogv
drwxr-xr-x. 2 eleiss eleiss     4096 Aug  7  2010 Pictures
-rw-rw-r--. 1 eleiss eleiss      618 Aug 11  2010 texput.log
drwx------. 2 eleiss eleiss     4096 May 17 23:31 VGAME
[eleiss@eleiss ~]$ ls -l | tail -n +2 | cut -b 1-10
-rw-------
drwxr-xr-x
drwxr-xr-x
drwxrwxr-x
drwxr-xr-x
-rw-rw-r--
drwxr-xr-x
-rw-rw-r--
drwx------
[eleiss@eleiss ~]$

tail command eliminates the first line from the output of ls -l command. As you know that the first ten characters of the output are the file type and permissions. The cut command extracts first ten characters from each line.


You may write to resources@eleiss.com for any Linux related queries.

advertisement