sort with tab field separator

Sjoerd Mullender sjoerd at acm.org
Sun Mar 23 12:37:29 UTC 2008


On 2008-03-23 00:06, Nicholas Robinson wrote:
> On Saturday 22 March 2008 21:38:46 Nicholas Robinson wrote:
>> On Saturday 22 March 2008 21:18:11 Amadeus W.M. wrote:
>>> You would think specifying tab as a field separator for sort would work
>>> like this:
>>>
>>> cat file | sort -k 3 -t "\t"
>>>
>>> It doesn't:
>>>
>>> sort: multi-character tab `\\t'
>>>
>>>
>>> So after a little search and some trial and error I got this to work:
>>>
>>> cat file | sort -k 3 -t "`/bin/echo -e '\t'`"
>>>
>>>
>>> For my own curiosity, can someone please illuminate me as to why the
>>> first incantation does not work as expected? Is there a more natural way
>>> to specify \t other than echo?
>> Take the double quotes out in your first attempt. So command becomes
>>
>> cat file | sort -k 3 -t \t
>>
>> Nick
> 
> Sorry, I was a little bit quick off the mark. The \t doesn't yield a tab 
> character (see below) as you were implying and I went along with in the first 
> example! If you take the double quotes out as I suggested, then the field 
> separator becomes the character t!
> 
> I think (being a little more cautious this time!) that you want:
> 
> \ followed by Ctrl V followed by Ctrl I
> 
> If I remember correctly, sort interprets a tab as a default field separator 
> anyway.
> 
> As to the why: it is because the -t takes an argument which is a character. 
> Putting double quotes around it stops the \ being elided and so \t as two 
> characters \ and t are presented to sort which is expecting only one 
> character. Hence its moan. Try echo "\t" and you will see what I mean.
> 
> In my second attempt above, the Ctrl V stops the tab character (Ctrl I) being 
> expanded on the command line and the \ joins the tab character to the t.
> 
> HTH
> 
> Nick
> 

Easier:
sort -k 3 -t $'\t'

See `man bash' and look for $'string'.

-- 
Sjoerd Mullender




More information about the fedora-list mailing list