【问题标题】:Perl regex in windows and linux issueWindows 和 linux 中的 Perl 正则表达式问题
【发布时间】:2021-10-11 23:12:19
【问题描述】:

我创建了一个简单的 perl 脚本来使用 Regex 并从文本文件中提取一个值。我已经使用 windows 开发了这个脚本,它在 windows 中运行良好

use strict;
use warnings;
use File::Slurp;

my $content = read_file("config.ini");

my $lin_targetdir = $1 if $content =~ m/targetDirectory\s*=\s*(.*)/;

print($lin_targetdir); # /opt/mypath  in linux i am getting this output

我的配置是

[prdConfig]
IP = xxxxxx
UserID = yyyyyy
password = "zzzzzzz"
targetDirectory = /opt/mypath

但是,当我在 Linux (centos 7) 中运行上述脚本时,脚本不会打印该值。我的代码出了什么问题?你能帮帮我吗?

【问题讨论】:

  • 它在我的 Debian 11 (Perl v5.32.1) 和 Windows 10 (Strawberry Perl v5.30) 上运行良好。
  • 预期的输出是什么,你想要什么?你得到了什么?
  • 在 linux 上,您可能正在针对具有 DOS 行结尾 (\r\n) 的配置文件运行它,因此 \r 被捕获,并且在打印出来时,将光标移回行并清除刚刚打印的内容。
  • 嗨@DaveMitchell,你救了我,你是对的。我刚刚用 dos2unix 覆盖了 config.ini 并运行了上面的内容。有效。太好了,谢谢
  • 可能有一些模块被设计用来读取 INI 文件,比你自制的版本更好。

标签: regex linux perl


【解决方案1】:

用正则表达式本身排除回车:

/targetDirectory\s*=\s*(\V*)/

Reference:

由于文档中指定的 Perl 5.10,\V[^\n\cK\f\r\x85\x{2028}\x{2029}] 相同,并且不应匹配任何 \n strong>、\r\f,以及 Ctrl+(Control char) (*nix)、0x850x20280x2029

替代方案:

/targetDirectory\s*=\s*([^\r\n]*)/

仅排除换行符和回车符。

【讨论】:

  • 确实如此。我同意你的看法。这有助于运行 doc2unix
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多