使用匹配找到只bash的子字符串 [英] Using match to find substrings in strings with only bash

查看:100
本文介绍了使用匹配找到只bash的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然我几乎可以肯定这已经涵盖,我似乎无法找到具体到这样的东西。正如我继续学习的bash我的旅程我不断寻找,我感到莫名其妙,为什么事情发生,他们做的方式部分。

Although I am almost sure this has been covered, I can't seem to find anything specific to this. As I continue my journey on learning bash I keep finding parts where I am baffled as to why things happen the way they do.

搜索和替换或只是匹配的子字符串,字符串中是最有可能的编写脚本时,你首先要做的事情之一。但是,试图坚持一个单一的语言或一套工具很难在bash做,因为你是能够解决多种方式大多数问题。我尽我所能保持为低电平尽可能使用bash。我遇到了一个障碍,我需要有人向我解释。

Searching and replacing or just matching sub-strings in strings is most likely one of the first thing you do when writing scripts. But, trying to stick to one single language or set of tools is difficult to do in bash, as you are able to solve most problem in multiple ways. I am doing my best to stay as low level as possible with bash. I have run into a snag that I need someone to explain to me.

这样的子字符串与匹配的bash搜索给了我不同的结果取决于常规的前pression我用,我不知道为什么。

Doing sub-string a search in bash with match gives me different results depending on the regular expression I use, and I am not sure why.

#!/bin/bash
Stext="Hallo World"
echo `expr "$Stext" : '^\(.[a-z]*\)'` # Hallo
echo `expr "$Stext" : '.*World'`      # 11

虽然这两个搜索词,的我觉得的,既没有返回他们所发现。为什么?

Although both search for a word, I think, both don't return what they find. Why?

推荐答案

这两个前pressions是等价的,所不同的是,你使用常规的前pression:

Both expressions are equivalent, the difference is the regular expression you use:

$ echo `expr "$Stext" : '^\(.[a-z]*\)'`
Hallo
$ echo `expr "$Stext" : '^.[a-z]*'`
5
$ echo `expr "$Stext" : '\(.*World\)'`
Hallo World
$ echo `expr "$Stext" : '.*World'`
11

正如你所看到的,括号是什么使差异要么返回比赛或比赛本身的长度。

As you can see, parentheses is what makes the difference to either return the length of the match or the match itself.

您可以在章高级Bash脚本编程指南10 找到更多的例子。

You can find more examples in Chapter 10 of the Advanced Bash-Scripting Guide.

这篇关于使用匹配找到只bash的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆