【问题标题】:bash to extract second half of namebash 提取名称的后半部分
【发布时间】:2018-07-27 21:11:31
【问题描述】:

好的,对于新的 High Sierra,我正在尝试编写一个脚本来自动删除占用硬盘空间的本地快照。我知道你可以使用 thinlocalsnapshots / 1000000000 4 进行缩小,但我觉得这只是一个创可贴。

所以我要做的是从以下位置提取日期 2018-02-##-######:

sudo tmutil listlocalsnapshots / 
com.apple.TimeMachine.2018-02-15-170531
com.apple.TimeMachine.2018-02-15-181655
com.apple.TimeMachine.2018-02-15-223352
com.apple.TimeMachine.2018-02-16-000403
com.apple.TimeMachine.2018-02-16-013400
com.apple.TimeMachine.2018-02-16-033621
com.apple.TimeMachine.2018-02-16-063811
com.apple.TimeMachine.2018-02-16-080812
com.apple.TimeMachine.2018-02-16-090939
com.apple.TimeMachine.2018-02-16-100459
com.apple.TimeMachine.2018-02-16-110325
com.apple.TimeMachine.2018-02-16-122954
com.apple.TimeMachine.2018-02-16-141223
com.apple.TimeMachine.2018-02-16-151309
com.apple.TimeMachine.2018-02-16-161040

我已经尝试过各种变体

 | awk '{print $ } (insert number after $)

随着

 | cut -d ' ' -f 10-.

如果您知道我在这里缺少什么,我将不胜感激

编辑:这是摆脱那些讨厌的本地快照的脚本。如果有人有兴趣,再次感谢:

#! /bin/bash

dates=`tmutil listlocalsnapshots /  | awk -F "." 'NR++1{print $4}'`

for dates in $dates
do
   tmutil deletelocalsnapshots $dates
done

【问题讨论】:

    标签: bash macos operating-system


    【解决方案1】:

    1- awk:您可以使用-F 选项指定字段分隔符,也可以打印一个子字符串

     awk -F. '{print $4}'
     awk '{print substr($0,23)}'
    

    2-cut:等价。

     cut -d. -f4
     cut -c23- 
    

    3- 纯bash(sloooooow!):同上。

    while IFS=. read s1 s2 s3 d; do echo "$d"; done
    while read line; do echo "${line:23}"; done
    

    在实践中,在您的用例中使用少量记录,速度不是问题,甚至可以使用纯 bash 或正则表达式(如在其他情况下)。随着记录数量的增加,awkcut 的更高速度变得明显。

    【讨论】:

      【解决方案2】:

      使用

      $ grep -oP '\d{4}-\d{2}-\d{2}-\d{6}$'
      2018-02-15-170531
      2018-02-15-181655
      2018-02-15-223352
      2018-02-16-000403
      2018-02-16-013400
      2018-02-16-033621
      2018-02-16-063811
      2018-02-16-080812
      2018-02-16-090939
      2018-02-16-100459
      2018-02-16-110325
      2018-02-16-122954
      2018-02-16-141223
      2018-02-16-151309
      2018-02-16-161040
      

      【讨论】:

        【解决方案3】:

        你很亲密:

        somecommand | cut -d"." -f4-
        # or
        somecommand | awk -F"." '{print $4}'
        

        您也可以尝试sed,但cut 就是为此而生的。

        【讨论】:

        • 谢谢沃尔特,完全忘了我可以添加什么来分隔!
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-26
        • 1970-01-01
        • 2012-09-07
        相关资源
        最近更新 更多