【问题标题】:Split a string having multiple delimeters using shell script使用 shell 脚本拆分具有多个分隔符的字符串
【发布时间】:2021-09-02 14:40:39
【问题描述】:
```

我有一个以下格式的字符串 aYbMTcDdHeMfs 其中 a,b,c,d,e 和 f 是任意长度的数字。 Y-> 年 MT-> 月 D-> 天 H-> 小时 M-> 分钟 S-> 秒

```

The string can have anything like

1H2M3S
1Y2MT3D4H5H6S
1Y20S 
.. so on.


Here the input has the same order of years,months,days,hours,minutes and seconds.

    If we want to fetch the value of years, months, days, hours, minutes, and seconds from the string then what would be the shell script to convert it into seconds?
    
    1H20S -> 3620
    
    10M200S -> 800
    
    10M100S -> 700

你能帮我找到那些脚本吗?

【问题讨论】:

  • 到目前为止你尝试了什么?请花点时间阅读how to ask
  • 你的目标是什么外壳?基本 POSIX sh?
  • 你如何从 1H20S 得到 3620 ?你是说秒吗?
  • MT转秒是什么意思?例如,二月的秒数少于七月。
  • 请澄清您的具体问题或提供更多详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: shell csv split


【解决方案1】:

您的规范不完整,但这里有一些想法可以帮助您入门:

#!/bin/bash
    
aYbMTcDdHeMfS(){
    x=${1//Y/*31536000+}
    x=${x//MT/*2628000+}
    x=${x//D/*86400+}
    x=${x//H/*3600+}
    x=${x//M/*60+}
    x=${x//S/+}
    x=${x%+}
    echo "$((x))"
}

aYbMTcDdHeMfS            1H  # 3600
aYbMTcDdHeMfS         15S3M  # 195
aYbMTcDdHeMfS        1H2M3S  # 3723
aYbMTcDdHeMfS 1Y2MT3D4H5H6S  # 37083606
aYbMTcDdHeMfS         1Y20S  # 31536020
aYbMTcDdHeMfS         1H20S  # 3620
aYbMTcDdHeMfS       10M200S  # 800
aYbMTcDdHeMfS       10M100S  # 700
<<'EOD' sed '
    s/[[:space:]]*//g
    s/Y/*31536000+/g
    s/MT/*2628000+/g
    s/D/*86400+/g
    s/H/*3600+/g
    s/M/*60+/g
    s/S/+/g
    s/+*$//
' | bc -l
1H
15S3M
1H2M3S
1Y2MT3D4H5H6S
1Y20S
1H20S
10M200S
10M100S
EOD

【讨论】:

  • 这里的字符串可以是: [aY][bM][cD][TdHeMfS] 在这种情况下,上述函数不适用于 aD
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-08
  • 2021-11-10
  • 1970-01-01
  • 1970-01-01
  • 2018-02-27
  • 1970-01-01
相关资源
最近更新 更多