How to define 'tab' delimiter with 'cut' in Bash?
Here is an example of using cut
to break input into fields using a space delimiter, and obtaining the second field:
cut -f2 -d' '
How can the delimiter be defined as a tab, instead of a space?
Two ways:
Press Ctrl+V and then Tab to use "verbatim" quoted insert.
cut -f2 -d' ' infile
or write it like this to use ANSI-C quoting:
cut -f2 -d$'t' infile
The $'...'
form of quotes isn’t part of the POSIX shell language (not yet), but works at least in ksh, mksh, zsh and Busybox in addition to Bash.
awk -F 't' '{ print $2 }' inputfile
This extracts the second tab-delimited field of each line of input from inputfile
.
Tab is the default.
See the cut man page.
-d delim
Use delim as the field delimiter character instead of the tab
character.
So you can just write
cut -f 2
More generically, without requiring any invisible characters: Use tr
to convert the delimiters to a format that can be specified more easily to cut
.
$ echo -e "atbtc" |tr 't' ' ' |cut -d' ' -f2
b
tr
is a simple, but powerful, character matching and replacement tool.
Alternatively, one could wrap cut in a function.
function getColumns ()
{
local -r delimiter="${1:?}"
local -r columns="${2:?}"
if [[ "$delimiter" == 't' || "$delimter" == "tab" ]]; then
cut "--fields=${columns}"
return
fi
cut "--delimiter=${delimiter}" "--fields=${columns}"
}
I use TAB
and cut
in these ways:
# quote the whole thing, use TAB escape
cut "-dt" -f 2
# just quote the tab escape
cut -d "t" -f 2
# Use Ctrl-V to quote Ctrl-I (TAB is Ctrl-I, see man ascii)
cut -d^V^I -f 2