Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I'm trying to make a shell script, I want to cut a string using the 'cut' unix command, as follows:

namecmpaux=$(echo $namecmp |cut -c0-19)

But when I run the shell tells me the following error:

cut: fields and positions are numbered from 1 
Try `cut - help 'for more information.

I remember previously used the 'cut' command using zero as the lower limit position, but now tells me that the command should start at 1. Why?, depends on the operating system? previously used SunOS and now i'm using ubuntu 12.04

share|improve this question
1  
Hmm, I don't see anything about field 0 in the cut man page on a solaris 8 system, but 0 works as the start of a range. The man page for GNU cut (i.e. linux) is quite clear that fields start with 1. Looks like you were relying on undocumented behaviour on SunOS. –  glenn jackman Mar 27 at 19:53

2 Answers 2

up vote 4 down vote accepted

No, it's the same in every cut implementation. Numbers start at one, it's just the Solaris' one will not complain if you provide 0 and will treat it as 1. Both 0 and 1 there means the first character, and 2 means the second character:

$ echo test | cut -c0-2
te
$ echo test | cut -c1-2
te

busybox cut or the cut builtin in ksh93 also don't complain. GNU cut just tries to be helpful in telling you that you probably don't have the right idea about what's the first index.

A real difference though is that GNU and busybox cut (at least as of 2014-03-27), count in bytes for -c, while Solaris or ksh cut count in characters (as POSIX requires).

$ echo 'Stéphane' | cut -c1-4
Sté
$ echo 'Stéphane' | busybox cut -c1-4
Sté
$ echo 'Stéphane' | ksh -c 'command /opt/ast/bin/cut -c1-4'
Stép

(in a UTF-8 locale, é (U+00E9) takes 2 bytes)

share|improve this answer

Yes, that might indeed be OS-dependent (or rather dependent on who wrote your version of cut).

If you take a look at man cut, you will see that cut from GNU's coreutils counts bytes, characters and fields from 1:

Use one, and only one of -b, -c or -f. [...] Each range is one of:
      N      N'th byte, character or field, counted from 1

Again, this might differ on a different system if its maintainers have decided to use an implementation of cut other than the GNU one, so better be safe and take a look at the manpage to be sure.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.