Cut command to specify the tab as the delimiter

showkey picture showkey · Jan 28, 2013 · Viewed 69.8k times · Source

There is a file which the delimiter is tab ,when i use the command

cut -d \t file.txt  #or  "\t"  or  "\\t"

I get this message

cut: you must specify a list of bytes, characters, or fields

Try `cut --help' for more information.

How to use the cut command?

Answer

bikeshedder picture bikeshedder · Jan 28, 2013

Cut splits the input lines at the given delimiter (-d, --delimiter).

To split by tabs omit the -d option, because splitting by tabs is the default.

By using the -f (--fields) option you can specify the fields you are interrested in.

echo -e "a\tb\tc" |cut -f 1 # outputs "a"
echo -e "a\tb\tc" |cut -f 2 # outputs "b"
echo -e "a\tb\tc" |cut -f 3 # outputs "c"
echo -e "a\tb\tc" |cut -f 1,3 # outputs "a\tc"
echo -e "a\tb\tc\td\te" |cut -f 2-4 # outputs "b\tc\td"

You can also specify the output delimiter (--output-delimiter) and get rid of lines not containing any delimiters (-s/--only-delimited)

echo -e "a\tb\tc\td\te" |cut -f 2-4 --output-delimiter=":" # outputs b:c:d

If you are interrested in the first field of your input file simply do...

cut -f 1 file.txt