修改sed语句?

时间:2014-03-22 08:46:10

标签: bash sed

我正在尝试修改以下sed语句以添加修改后的字符串。 $ DIRCONTENT是:

{"hash": "79e7b189ab3985f4bf753ba706da07ed", "thumb_exists": false, "bytes": 0, "path": "/", "is_dir": true, "size": "0 bytes", "root": "app_folder", "contents": [{"revision": 135, "rev": "8714372dc4", "thumb_exists": false, "bytes": 0, "modified": "Fri, 25 Oct 2013 00:05:18 +0000", "path": "/home", "is_dir": true, "icon": "folder", "root": "dropbox", "size": "0 bytes"}, {"revision": 1, "rev": "114372dc4", "thumb_exists": false, "bytes": 1223, "modified": "Mon, 16 Sep 2013 21:00:23 +0000", "client_mtime": "Mon, 16 Sep 2013 21:00:23 +0000", "path": "/serial.c", "is_dir": false, "icon": "page_white_code", "root": "dropbox", "mime_type": "text/x-csrc", "size": "1.2 KB"}], "icon": "folder"}

sed语句是

echo "$DIR_CONTENT" | sed 's/\\"/\\u0022/' | sed -n 's/.*"bytes": *\([0-9]*\),.*"path": *"\([^"]*\)",.*"is_dir": *\([^"]*\),.*/\2:\3;\1/p'

返回

/home:true;0
/serial.c:false;1223

我想添加"修改"字段,然后返回

/home:true;0;Fri, 25 Oct 2013 00:05:18 +0000
/serial.c:false;1223;Mon, 16 Sep 2013 21:00:23 +0000

3 个答案:

答案 0 :(得分:1)

试试这个sed命令:

$ echo "$DIR_CONTENT" | sed 's/\\"/\\u0022/' | sed -n 's/.*"bytes": *\([0-9]*\),.*"modified": *"\([^"]*\).*"path": *"\([^"]*\)",.*"is_dir": *\([^"]*\),.*/\3:\4;\1;\2/p'
/serial.c:false;1223;Mon, 16 Sep 2013 21:00:23 +0000

答案 1 :(得分:1)

修改后的sed查询可以是这样的:

echo "$DIR_CONTENT" | sed 's/\\"/\\u0022/' | sed -n 's/.*"bytes": *\([0-9]*\),.*"modified"\([^"]*\)",.*"path": *"\([^"]*\)",.*"is_dir": *\([^"]*\),.*/\3:\4;\1;\2/p'

答案 2 :(得分:0)

echo "$DIR_CONTENT" | sed -nr '
    s#.*"contents": \[([^]]*)\].*#\1#
    :X
    h
    s#(\{[^}]*}).*#\1#
    s#"([^"]*)": ("?[^"]*"?),#\1\a\2\n#g
    s#.*bytes\a([^\n]*).*modified\a([^\n]*).*path\a([^\n]*).*is_dir\a([^\n]*).*#\3:\4;\1;\2#
    s#"##gp
    g
    /(\{[^}]*}), (.*)/{ s##\2#; bX }
'
/home:true;0;Fri, 25 Oct 2013 00:05:18 +0000
/serial.c:false;1223;Mon, 16 Sep 2013 21:00:23 +0000