简体   繁体   English

使用grep从Shell脚本中的正则表达式中提取组

[英]Extracting group from regex in shell script using grep

I want to extract the output of a command run through shell script in a variable but I am not able to do it. 我想提取通过shell脚本运行的命令的输出变量,但是我无法做到。 I am using grep command for the same. 我使用grep命令相同。 Please help me in getting the desired output in a variable. 请帮助我获取所需的变量输出。

x=$(pwd)
pw=$(grep '\(.*\)/bin' $x)
echo "extracted is:"
echo $pw

The output of the pwd command is /opt/abc/bin/ and I want only /root/abc part of it. pwd命令的输出是/opt/abc/bin/ ,我只希望它的/root/abc部分。 Thanks in advance. 提前致谢。

使用dirname获取路径,而不是路径的最后一段。

You can use: 您可以使用:

x=$(pwd)
pw=`dirname $x`
echo $pw

Or simply: 或者简单地:

pw=`dirname $(pwd)`
echo $pw

All of what you're doing can be done in a single echo : 您正在做的所有事情都可以在单个echo

echo "${PWD%/*}"

$PWD variable represents current directory and %/* removes last / and part after last / . $PWD变量代表当前目录和%/*删除最后/和最后的后部分/

For your case it will output: /root/abc 对于您的情况,它将输出: /root/abc

The second (and any subsequent) argument to grep is the name of a file to search, not a string to perform matching against. grep的第二个(以及任何后续)参数是要搜索的文件的名称,而不是要执行匹配的字符串。

Furthermore, grep prints the matching line or (with -o ) the matching string, not whatever the parentheses captured. 此外, grep打印匹配的行或(使用-o )匹配的字符串,而不捕获括号。 For that, you want a different tool. 为此,您需要其他工具。

Minimally fixing your code would be 最小修复您的代码将是

x=$(pwd)
pw=$(printf '%s\n' "$x" | sed 's%\(.*\)/bin.*%\1%')

(If you only care about Bash, not other shells, you could do sed ... <<<"$x" without the explicit pipe; the syntax is also somewhat more satisfying.) (如果只关心Bash,而不关心其他shell,则可以在没有显式管道的情况下进行sed ... <<<"$x" ;语法也更令人满意。)

But of course, the shell has basic string manipulation functions built in. 但是,当然,shell具有内置的基本字符串操作功能。

pw=${x%/bin*}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM