从日志文件中提取日志时间

时间:2016-08-01 08:17:01

标签: linux bash awk

如何仅从类似字符串中提取时间部分。

{
  "name": "myApp",
  "version": "0.0.0",
  "main": "index.html",
  "ignore": [
    "**/.*",
    "node_modules",
    "bower_components"
  ],
  "dependencies": {
    "jquery": "~2.2",
    "lodash": "~4.9",
    "bootstrap": "^3.3.6",
    "angular": "~1.5",
    "angular-route": "~1.5",
    "angular-animate": "~1.5",
    "angular-resource": "~1.5",
    "angular-cookies": "^1.5.7",
    "angular-mocks": "~1.5",
    "angular-bootstrap": "~1.3.1",
    "moment": "~2.12",
    "less.js": "~2.6",
    "font-awesome": "~4.5",
    "d3": "^3.5.17"
  }
}

我只想从日志中获取 15:55:42.079 这部分内容。

3 个答案:

答案 0 :(得分:3)

你可以试试这个:

awk -F']| ' '{print $2}' <<< "STRING"

<强>测试

$ awk -F']| ' '{print $2}' <<< "[20/06/2016 15:55:42.079] Echo test request"
15:55:42.079

答案 1 :(得分:2)

sed也是你的朋友:

$ sed -E 's/^[^[:blank:]]*[[:blank:]]([^]]*)\].*$/\1/' 38693974
15:45:42.079
15:55:12.079
15:55:42.079
15:56:42.079

答案 2 :(得分:1)

最简单的方法是使用参数扩展子串删除,例如:

var="[20/06/2016 15:55:42.079] Echo test request"
tm=${var%]*}     ## remove all from right including ']'
tm=${tm#* }      ## remove all from left including ' '
echo "time $tm"  ## your time is now in $tm

操作上方${var%]*}使用%运算符,该运算符从右到左依次删除所有'*',直到达到]。现在,对于字符串[20/06/2016 15:55:42.079的剩余部分,您只需要#运算符,该运算符从头开始从左到右删除。在此,我们删除了'*'(所有内容),包括' '仅在变量15:55:42.079中留下tm

如果您有疑问,请告诉我。