ZSH子串提取

目标

在ZSH脚本中,对于给定的args,我想获得第一个字符串和其余字符串.

例如,当脚本命名为test时

sh test hello

应该提取h和ello.

ZSH manual

http://zsh.sourceforge.net/Doc/zsh_a4.pdf

说:

Subscripting may also be performed on non-array values,in which case the subscripts specify a
substring to be extracted. For example,if FOO is set to ‘foobar’,then ‘echo $FOO[2,5]’ prints
‘ooba’.

Q1

所以,我在一个名为test的文件中编写了一个shell脚本

echo $1
echo $1[1,1]

终奌站:

$sh test hello
hello
hello[1,1]

结果失败了.代码有什么问题?

Q2

另外我不知道如何从n到最后一个提取subString.也许我必须使用正则表达式拆分阵列?

编辑:Q3

这可能是另一个问题,所以如果启动新线程是正确的,我会这样做.

感谢@skishore这是进一步的代码

#! /bin/zsh

echo $1

ARG_FirsT=`echo $1 | cut -c1`
ARG_REST=`echo $1 | cut -c2-`
echo ARG_FirsT=$ARG_FirsT
echo ARG_REST=$ARG_REST

if $ARG_FirsT = ""; then
  echo nullArgs
else
  if $ARG_FirsT = "@"; then
    echo @Args
  else
    echo regularargs
  fi
fi

我不确定如何将字符串贵重物品与字符串进行比较,但对于给定的args你好

结果:

command not found: h

代码有什么问题?

EDIT2:

我发现的正确

#! /bin/zsh

echo $1

ARG_FirsT=`echo $1 | cut -c1`
ARG_REST=`echo $1 | cut -c2-`
echo ARG_FirsT=$ARG_FirsT
echo ARG_REST=$ARG_REST

if [ $ARG_FirsT ]; then
  if [ $ARG_FirsT = "@" ]; then
    echo @Args
  else
    echo regularargs
  fi
else
  echo nullArgs
fi

EDIT3:

作为整体的结果,这就是我对这个问题所做的.

https://github.com/kenokabe/GitSnapShot

GitSnapShot是GIT命令的ZSH瘦包装器,可以更简单,更简单地使用

解决方法

您可以使用cut命令:
echo $1 | cut -c1 
echo $1 | cut -c2-

使用$()将这些值分配给变量:

ARG_FirsT=$(echo $1 | cut -c1)
ARG_REST=$(echo $1 | cut -c2-)
echo ARG_FirsT=$ARG_FirsT
echo ARG_REST=$ARG_REST

你也可以用反引号替换$(),但建议使用前者,后者因嵌套问题而有所弃用.

相关文章

1、安装Apache。 1)执行如下命令,安装Apache服务及其扩展包...
一、先说一下用ansible批量采集机器信息的实现办法: 1、先把...
安装配置 1. 安装vsftpd 检查是否安装了vsftpd # rpm -qa | ...
如何抑制stable_secret读取关键的“net.ipv6.conf.all.stabl...
1 删除0字节文件 find -type f -size 0 -exec rm -rf {} ...
## 步骤 1:安装必要的软件包 首先,需要确保系统已安装 `dh...