【问题标题】:Extracting multiple variables from a changing string in bash从Bash中的更改字符串中提取多个变量
【发布时间】:2015-08-27 15:23:32
【问题描述】:

我在一个文件中有多个这样的字符串,每行一个:

[random string] was [failed/passed] 1y 2mo 3d 1h 51m 2s ago [some string]

现在我要做的是提取 6 个变量(年、月、日、小时、分钟、秒)中的持续时间,以使用“日期”函数计算日期。 我还想在变量(例如 O/1)中获取通过/失败。

我遇到了3个问题:

  • 我无法读取包含这些字符串的文件中的每一行(for 循环不能很好地工作......也许一段时间会更好)
  • 如果我设法读取了一个字符串,我尝试使用 cut 对其进行解析,但我不知道如何去掉字母 (y,mo,h...) 并只保留数字。

  • 持续时间格式是可变的;不到一年时,它可能是 1mo 2h 3s,或 1y 3d 58m 3s,或 3h 5s ......等等。我不知道如何处理这种可变性。我猜该命令必须检查字母并按其功能分配,然后将 0 分配给不存在的字母。

非常感谢您的帮助!

【问题讨论】:

    标签: python string perl date datetime


    【解决方案1】:

    这是我认为对你有用的perl 代码。

    #!/usr/bin/perl
    my $string = <STDIN>;
    chomp $userword; # Get rid of newline character at the end
    @arr = $string =~ /(passed|failed).+?([\d]+[yY].)?([\d]+(?:mo|MO).)?([\d]+[dD].)?([\d]+[hH].)?([\d]+[mM].)?([\d]+[sS])/g;
    $arr_len = scalar @arr;
    print "Result: $arr[0]\n";
    for($i=1;$i<=$arr_len;$i=$i+1){
        $arr[$i]=~/(\d+)([A-Za-z]*)/g;
        if ( $2 eq "y" | $2 eq "Y" ) {
            print "Year is $1\n";
        } elsif ( $2 eq "mo" | $2 eq "MO") {
            print "Month is $1\n";
        } elsif ( $2 eq "d" | $2 eq "D") {
            print "Day is $1\n";
        } elsif ( $2 eq "h" | $2 eq "H") {
            print "Hour is $1\n";
        } elsif ( $2 eq "m" | $2 eq "M") {
            print "Minute is $1\n";
        } elsif ( $2 eq "s" | $2 eq "S" ) {
            print "Second is $1\n";
        }
    }
    

    我尝试了三种不同的输入,它们是:

    [random string] was failed 1y 2mo 3d 1h 51m 2s ago [some string]
    
    [random string] was passed 2mo 3d 1h 51m 2s ago [some string]
    
    asd  sd asdg s passed 1y 2mo 3d 1h 2s
    
    [random string] was failed 1y 4d 5h 3m 2s ago [some string]
    

    相应地显示所有三个的输出:

    Result: failed
    Year is 1
    Month is 2
    Day is 3
    Hour is 1
    Minute is 51
    Second is 2
    
    Result: passed
    Month is 2
    Day is 3
    Hour is 1
    Minute is 51
    Second is 2
    
    
    Result: passed
    Year is 1
    Month is 2
    Day is 3
    Hour is 1
    Second is 2
    
    
    Result: failed
    Year is 1
    Day is 4
    Hour is 5
    Minute is 3
    Second is 2
    

    这里有几件事:

    1. 我没有使用过switch,因为它可能会报错Can't locate Switch.pm in @INC (you may need to install the Switch module)
    2. 我已尽力简化正则表达式,所以如果有人可以建议更好的正则表达式来选择,请发表评论。
    3. 这也是我第一次尝试在perl 中编程。如果有人找到改进代码的方法,请建议我。我将不胜感激。

    【讨论】:

    • 感谢您的回答!不幸的是,这在持续时间为例如 1y 4d 5h 3m 2s 时不起作用......另外,你知道如何获得失败/通过结果吗?
    • @libussa,代码在1y 4d 5h 3m 2s 期间可以正常工作。只需查看我在第一条评论中提供的链接中的运行代码即可。另外,我已经更新它以获得结果。
    猜你喜欢
    • 2022-01-06
    • 2013-01-14
    • 2015-05-12
    • 1970-01-01
    • 2021-05-27
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    相关资源
    最近更新 更多