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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
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 should just write
cut -f 2
Method 3
awk -F 't' '{ print $2 }' inputfile
This extracts the second tab-delimited field of each line of input from inputfile.
Method 4
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.
Method 5
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}"
}
Method 6
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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0