Bash - 在perl regex中使用变量和匹配组 [英] Bash - use variable in perl regex together with matching groups

查看:228
本文介绍了Bash - 在perl regex中使用变量和匹配组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在stackoverflow上的第一篇文章,请原谅我,如果我错过了一些重要的东西。
我目前坚持下面的问题。我们的目标是根据我使用 find 准备的文件列表来动态替换端口号。这些文件中的所有端口都以数字4开始,并有5位数字。

现在,棘手的部分,我只替换了数字#2和#3例如:

 文件中的旧端口:40380,40381 
新端口in file:41580,40381

我正在使用Sun Solaris 5.10,因此我更喜欢perl for inline replacements



最后一个关键问题是:如何将$ 1(group 1)+ $ PIN_PINNO + $ 3(group 3)组合起来,从而得到如下结果:4 15 80

  NEW_PINNO = 15 
LOGI = $ HOME / filelist.txt
$ b $ $ cat $ LOGI`文件中的b#端口替换

do
perl -pe's / [\:\> \ =] \s *(4) (\d {2})(\d {2})\b / $ 1 $ {NEW_PINNO} $ 3 / g'$ file


$ b很多在此先谢谢了解决方案

perl -pse's / [:> =] \s * \K(\ d)\d \d(\d\d)\ b / $ 1 $ pin $ 2 / gx' - -pin =$ new_pinnofile





测试

  new_pinno = 15 
perl -pse's / [:> =] \s * \K(\ d)\d\d(\d\d)\b / $ 1 $ pin $ 2 / gx ' - -pin =$ new_pinno<< END
var1 = 40380
var2 = 40381
END





  var1 = 41580 
var2 = 41581

注意


  • 你不应该在shell中使用ALL_CAPS_VARNAMES ,留下那些由shell保留。有一天,你会使用 PATH = something ,然后想知道为什么你的脚本坏了。
  • 和@ 123的评论已验证。这是从文件读取行的安全方式:

      while read -r file;做
    perl ...$ file
    完成< $ LOGI

    ref: http://mywiki.wooledge.org/DontReadLinesWithFor



this is my first post on stackoverflow, please forgive me if I missed something important. I am currently stuck with the follwing issue. The goal is, to replace port numbers dynamically based on a filelist I prepared with find. All of the ports in those files, start with the number "4" and have 5 digits.

Now the tricky part, I am replacing only digit #2 and #3, and keep positions 1, 4 and 5. Examples:

old port in file: 40380, 40381
new port in file: 41580, 40381

I am working on Sun Solaris 5.10 therefore I prefer perl for inline replacements

Finally the key question: how can I combine $1 (group 1) + $PIN_PINNO + $3 (group 3) so that the result would be: 41580

NEW_PINNO=15
LOGI=$HOME/filelist.txt

# port replacement
for file in `cat $LOGI`
do
    perl -pe 's/[\:\>\=]\s*(4)(\d{2})(\d{2})\b/$1${NEW_PINNO}$3/g' $file
done

many thanks in advance

解决方案

perl -pse 's/ [:>=]\s* \K (\d)\d\d(\d\d) \b/$1$pin$2/gx' -- -pin="$new_pinno" file

Testing

new_pinno=15
perl -pse 's/ [:>=]\s* \K (\d)\d\d(\d\d) \b/$1$pin$2/gx' -- -pin="$new_pinno" <<END
var1=40380
var2=40381
END

var1=41580
var2=41581

Notes

  • you should not use ALL_CAPS_VARNAMES in the shell, leave those to be reserved by the shell. One day, you'll use PATH=something and then wonder why your script is broken.
  • and @123's comment is valid. This is the safe way to read lines from a file:

    while read -r file; do
        perl ... "$file"
    done < "$LOGI"
    

    ref: http://mywiki.wooledge.org/DontReadLinesWithFor

这篇关于Bash - 在perl regex中使用变量和匹配组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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