在一个多变量替换 [英] multiple replacements on a single variable

查看:114
本文介绍了在一个多变量替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关以下变量:

VAR =/路径/要/我的/文档001_extra.txt

我需要的 / [斜杠]之间以及 _ [下划线]只有部分。
此外, - [冲刺]需要被剥离

i need only the parts between the / [slash] and the _ [underscore]. Also, the - [dash] needs to be stripped.

在换句话说:文件001

这是我迄今为止:

VAR =$ {VAR ## * /}

VAR =$ {VAR%_ *}

VAR =$ {VAR / - /}

这工作得很好,但我在寻找,将饶了我一个更紧凑的替代模式的三重 VAR = ...

which works fine, but I'm looking for a more compact substitution pattern that would spare me the triple var=...

使用的SED,AWK,剪切等或许会更有意义,但我正在寻找一个纯bash的解决方案。

Use of sed, awk, cut, etc. would perhaps make more sense for this, but I'm looking for a pure bash solution.

根据需要GNU bash的工作,版本51年3月2日(1)-release

Needs to work under GNU bash, version 3.2.51(1)-release

推荐答案

编辑您的问题谈的模式,而不是常规的前pressions之后,现在我将告诉你如何的真正的使用常规的前pressions在庆典:)

After editing your question to talk about patterns instead of regular expressions, I'll now show you how to actually use regular expressions in bash :)

[[ $var =~ ^.*/(.*)-(.*)_ ]] && var="${BASH_REMATCH[@]:1:2}"

参数扩展就像你使用previously可惜不能嵌套在庆典(除非你用不明智的评估黑客,甚至然后它会比上面的线)不太清楚。

Parameter expansions like you were using previously unfortunately cannot be nested in bash (unless you use ill-advised eval hacks, and even then it will be less clear than the line above).

=〜运算符执行左边的字符串,并在右侧的普通前pression之间的匹配。在常规的前pression括号定义匹配组。如果匹配成功,退出状态 [...] 为零,因此code以下的&安培; &安培; 被执行。 (提醒:不要混淆进程退出状态的0 =成功,非零=失败与公约的共同布尔约定0 =假1 =真。)

The =~ operator performs a match between the string on the left and the regular expression on the right. Parentheses in the regular expression define match groups. If a match is successful, the exit status of [[ ... ]] is zero, and so the code following the && is executed. (Reminder: don't confuse the "0=success, non-zero=failure" convention of process exit statuses with the common Boolean convention of "0=false, 1=true".)

BASH_REMATCH 是,在成功地定期-EX pression匹配庆典设置一个数组参数。该阵列的第一个元素包含由常规的前pression匹配全文;以下每个元素包含对应捕获组中的内容。

BASH_REMATCH is an array parameter that bash sets following a successful regular-expression match. The first element of the array contains the full text matched by the regular expression; each of the following elements contains the contents of the corresponding capture group.

$ {foo的[@]:X:Y} 参数扩展产生的数组是元素,从索引 X 。在这种情况下,它只是写的一小段路 $ {BASH_REMATCH [1]} $ {BASH_REMATCH [2]} 。 (另外,虽然 VAR = $ {BASH_REMATCH [*]:1:2} 会工作为好,我倾向于使用 @ 反正强化的事实,你几乎总是要使用 @ 而不是 * 在其他情况下。 )

The ${foo[@]:x:y} parameter expansion produces y elements of the array, starting with index x. In this case, it's just a short way of writing ${BASH_REMATCH[1]} ${BASH_REMATCH[2]}. (Also, while var=${BASH_REMATCH[*]:1:2} would have worked as well, I tend to use @ anyway to reinforce the fact that you almost always want to use @ instead of * in other contexts.)

这篇关于在一个多变量替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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