cut

From NetBSD Wiki

Jump to: navigation, search

The cut(1) command can take certain parts of each line of a file and output only those parts.

Basically cut selects which "columns" to output of a file. Columns are either characters or records separated by some special character.

An example will make this more clear:

$ echo 'abcdef' | cut -c 1,5,6
aef

The above command cuts the columns numbered 1, 5 and 6. These correspond to the character positions of a, e and f.

echo 'root:*:0:0:Charlie &:/root:/bin/ksh' | cut -f 1,5,6 -d :
root:Charlie &:/root

The above command cuts the columns numbered 1, 5 and 6, but the -f instructs it not to look at character columns, but to use the ':' character as a column separator.

The default column separator for the -f form if you don't supply -d is to use the tab character.

There is a third form of the cut command. With this you use the -b switch. This indicates the byte column numbers. This is only different from the -c switch if you're using a multibyte character set (or escape sequences, maybe). It's not useful for binary files, because it will interpret any character 10 (line feed) as a newline anyway.

Note: The columns to select are arguments for the -f, -c or -b switches, so you can't do something like

$ echo 'foo' | cut -f -d : 1,2,3
cut: [-cf] list: illegal list value

Other examples

You can use cut directly on files too, of course. Then it will cut every line.

$ cat foo
foo
bar
$ cut -c 1,3 foo
fo
br

The example of the passwd entry works on the entire passwd file too, of course:

$ cut -f 1,5,6 -d : /etc/passwd 
root:Charlie &:/root
toor:Bourne-again Superuser:/root
daemon:The devil himself:/
operator:System &:/usr/guest/operator
...

Normally, in the -f mode, cut outputs lines without delimiters as-is:

$ cat foo
a:b:c
This line doesn't contain a delimiter!
d:e:f
$ cut -f 1,3 -d : foo
a:c
This line doesn't contain a delimiter!
d:f

You can change this behaviour with the -s switch. This tells cut to include only 'sane' lines:

$ cut -f 1,3 -d : -s foo
a:c
d:f

See also

View source code (Please report any bugs or suggestions here).

Retrieved from "http://wiki.netbsd.se/cut"
Personal tools