我正在尝试制作一个 shell 脚本,我想使用 'cut' unix 命令来剪切字符串,如下所示:
namecmpaux=$(echo $namecmp |cut -c0-19)
Run Code Online (Sandbox Code Playgroud)
但是当我运行 shell 时,会出现以下错误:
cut: fields and positions are numbered from 1
Try `cut - help 'for more information.
Run Code Online (Sandbox Code Playgroud)
我记得以前使用'cut'命令使用零作为下限位置,但现在告诉我该命令应该从1开始。为什么?取决于操作系统?以前使用 SunOS,现在使用 ubuntu 12.04
不,每个实现都是一样的cut
。数字从 1 开始,只是 Solaris 不会抱怨如果您提供 0 并将其视为 1。 Both0
和1
there 表示第一个字符,并2
表示第二个字符:
$ echo test | cut -c 0-2\nte\n$ echo test | cut -c 1-2\nte\n
Run Code Online (Sandbox Code Playgroud)\n\nbusybox
cut
或者cut
内置的ksh93
也不要抱怨。GNUcut
只是试图帮助您告诉您,您可能对第一个索引没有正确的了解。
但真正的区别是 GNU 和 busybox cut
(至少截至 2014 年 3 月 27 日)以字节为单位计数-c
,而 Solaris 或 kshcut
以字符为单位计数(按照 POSIX 的要求)。
$ echo 'St\xc3\xa9phane' | cut -c 1-4\nSt\xc3\xa9\n$ echo 'St\xc3\xa9phane' | busybox cut -c 1-4\nSt\xc3\xa9\n$ echo 'St\xc3\xa9phane' | ksh -c 'command /opt/ast/bin/cut -c 1-4'\nSt\xc3\xa9p\n
Run Code Online (Sandbox Code Playgroud)\n\n(在 UTF-8 语言环境中,\xc3\xa9 (U+00E9) 占用 2 个字节)
\n