linux - 如何找到单词在字符串中的位置?

标签 linux shell unix gnu

例如,如果我有变量

var="dog cat owl fish"

我想输入“cat”(由空格分隔的字符串中的第二个单词)并返回“2”,我该如何在没有 bash 的 shell 脚本中执行此操作?

最佳答案

“没有 bash”是什么意思?

以下内容适用于 bash、dash 和 ksh:

#!/bin/____  <- insert your shell here

input=$1
var="dog cat owl fish"

i=1
set -f
for word in $var ; do
    if [ "$word" = "$input" ] ; then
        echo $i
    fi
    i=$((i+1))
done

set -f 防止 $var 中的 * 进行路径名扩展。在 zsh 中,您需要 set -o SH_WORD_SPLIT 1 在 for 循环中拆分 $var

关于linux - 如何找到单词在字符串中的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52821275/

相关文章:

linux - 无法在ubuntu中启动mongo shell

linux - 在进程终止时哪个先发生?删除子进程和任务或调用 atexit 函数?

python - 在 bash 脚本中执行 python

javascript - 排列/格式化 html 和 js 代码

c++ - 如何在 Linux 中反汇编二进制可执行文件以获取汇编代码?

python - 从 Python 脚本如何运行其他 Python 脚本?

linux - Debian Bash Shell 变量替换错误

linux:获取一个脚本,以便能够向用户询问文件名,然后打开该文件

linux - Bash/Shell 脚本 - 如何操作文本文件中的值

linux - 如何在文件中查找匹配项,然后为该匹配项添加后缀