Bash expr index命令

g5t*_*mas 2 bash

我试图使用Bash'expr index"获取索引位置.

例如

$ echo `expr index "Info.out.2014-02-08:INFO|SID:sXfzRjbmKbwX7jyaW1sog7n|Browser[Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0]" Mozilla`
Run Code Online (Sandbox Code Playgroud)

我试图获取单词"Mozilla"的索引位置,然后使用索引值获取子字符串.

我得到的结果是4.是否是Info之后的问题?我该如何解决这个问题?

我按照Advanced Bash脚本指南www.tldp.org/LDP/abs/html/进行了操作.见表B-5.字符串操作

expr index"$ string"$ substring $ substring*中第一个字符的$ string中的数字位置匹配[0如果不匹配,则第一个字符计为位置1]

我尝试过一些简单的东西,但它确实有用.

我在cygwin中运行bash.

$ ./bash --version
GNU bash, version 4.1.10(4)-release (i686-pc-cygwin)
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Run Code Online (Sandbox Code Playgroud)

谢谢.

Cha*_*ffy 10

一般来说,expr index除非你有充分的理由,否则你不应该使用.

例如,假设您想获取浏览器名称.

s="Info.out.2014-02-08:INFO|SID:sXfzRjbmKbwX7jyaW1sog7n|Browser[Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0]"

# strip everything up to and including the first instance of 'Browser['
browser="${s#*Browser[}"

# strip everything after the first ']', again, inclusive
browser="${browser%%]*}"

# ...and show the result...
echo "$browser"
Run Code Online (Sandbox Code Playgroud)

这将返回:

Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0
Run Code Online (Sandbox Code Playgroud)

如果你真的想要知道有多少字符优先Mozilla,好了,你也可以这样做:

s="Info.out.2014-02-08:INFO|SID:sXfzRjbmKbwX7jyaW1sog7n|Browser[Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0]"

# strip everything after the first instance of 'Mozilla'
prefix=${s%%Mozilla*}

# count number of characters in the string
index=${#prefix}

# ...and show the result...
echo "$index"
Run Code Online (Sandbox Code Playgroud)

这应该回来了61.

对于上述示例的"为什么"和"如何",请参阅BashFAQ#73.


|相比之下,按照分隔符进行拆分,我个人会选择使用read,如BashFAQ#1中所述:

s="Info.out.2014-02-08:INFO|SID:sXfzRjbmKbwX7jyaW1sog7n|Browser[Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0]"
IFS='|' read -r _ _ browser _
echo "$browser"
Run Code Online (Sandbox Code Playgroud)

......会发出......

Browser[Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0]
Run Code Online (Sandbox Code Playgroud)


Kev*_*vin 5

expr index命令搜索您的第一个字符串,查找第二个字符串中任何字符的第一次出现。在这种情况下,它识别出字符“Mozilla”中的“o”与“Info.out...”中的第 4 个字符匹配。

这使用它作为测试,看看会发生什么。它将返回 4 作为 'd' 的第一个匹配项:

echo `expr index "abcdefghijklmnopqrstuvwxyz" xyzd`
Run Code Online (Sandbox Code Playgroud)

这个应该做你想做的:

echo "Info.out.2014-02-08:INFO|SID:sXfzRjbmKbwX7jyaW1sog7n|Browser[Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0]" | grep -o -b Mozilla
Run Code Online (Sandbox Code Playgroud)

echo 将您的字符串放入 stdout,因此它可以通过管道传输到 grep。

-b 打印显示的字符串的字节偏移量。

-o 确保仅打印匹配部分。