bash 在Unix中提取变量中两个字符串之间的部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31669103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:22:12  来源:igfitidea点击:

Extract part between two strings in a variable in Unix

bashunix

提问by Noobie

I have a string,

我有一根绳子,

tester_one="update set_tables set abc=7 where bcd=9"

Here I wish to extract only the part between "set" and "where",

这里我只想提取“set”和“where”之间的部分,

abc=7

I tried a couple of Unix commands, but it picked up any occurrences of setor where encountered, before the part where I want it to pick up.

我尝试了几个 Unix 命令,但它在我希望它选择的部分之前选择了任何出现的set或遇到的地方。

I have an idea on how to do it Java but I am lost in Unix as I am new to this.

我对如何使用 Java 有一个想法,但我在 Unix 中迷失了方向,因为我是新手。

采纳答案by viraptor

You can get it out with sed. Something like:

你可以用 sed 把它弄出来。就像是:

echo "$tester_one" | sed 's/.* set \(.*\) where .*//'

回答by John1024

Using sed

使用 sed

$ echo "$tester_one" | sed -E 's/.*set (.*) where.*//'
abc=7

To capture it in a variable:

要在变量中捕获它:

$ new=$(echo "$tester_one" | sed -E 's/.*set (.*) where.*//')
$ echo $new
abc=7

Using awk

使用 awk

$ echo "$tester_one" | awk '{sub(/.*set /,""); sub(/ where.*/,""); print;}'
abc=7

Using grep -P

使用 grep -P

If your grep supports the -P(perl-like) option:

如果您的 grep 支持-P(perl-like) 选项:

$ echo "$tester_one" | grep -oP '(?<=set ).*(?= where)'
abc=7 

回答by Jahid

Using Bash Pattern Matching:

使用Bash 模式匹配

#!/bin/bash
tester_one="update set_tables set abc=7 where bcd=9"
pat=".* set (.*) where"
[[ $tester_one =~ $pat ]]
echo "${BASH_REMATCH[1]}"

回答by fedorqui 'SO stop harming'

You can also use setand whereas field separators and print the field that lies in between them:

您还可以使用setwhere作为字段分隔符并打印位于它们之间的字段:

$ awk -F"set | where" '{print }' <<< "update set_tables set abc=7 where bcd=9"
abc=7

回答by ghoti

As with your other question, this can be achieved in pure bash, without the use of external tools like sed/awk/grep.

您的其他问题一样,这可以在纯 bash 中实现,而无需使用 sed/awk/grep 等外部工具。

#!/usr/bin/env bash

tester_one="update set_tables set abc=7 where bcd=9"

output="${tester_one#* set }"
output="${output% where }"

echo "$output"

Note the spaces around "set" and "where" in the parameter expansion lines. As you might expect, you'll need to be careful with this if the $tester_onevariable contains the distinct "set" or "where" in places that you don't expect them.

注意参数扩展行中“set”和“where”周围的空格。如您所料,如果$tester_one变量在您不希望它们的地方包含不同的“set”或“where”,则需要小心处理。

That said, I like Jahid's answerbetter. :-)

也就是说,我更喜欢贾希德的回答。:-)