【问题标题】:Converting key value pair using sed or awk使用 sed 或 awk 转换键值对
【发布时间】:2020-07-17 18:21:34
【问题描述】:

寻找 sed 或 awk 表达式以将键值转换为特定格式。在这种情况下,pass 没有值,所以它应该显示一个空字符串。

输入:

login: me pass: time: Wed 2020 07 message: There is a cat in the house

期望的输出:

login="me" pass="" time="Wed 2020 07" message="There is a cat in the house"

【问题讨论】:

  • 你有没有为此尝试过?
  • 尝试在python中进行拆分,但并未涵盖所有情况...

标签: regex bash shell awk sed


【解决方案1】:

使用 GNU sed:

echo "login: me pass: time: Wed 2020 07 message: There is a cat in the house" |
sed -E 'G; s/ [[:alpha:]][[:alnum:]]*:/\n&/g; s/: ?([^\n]*)\n/="\1"/g'

打印:

login="me" pass="" time="Wed 2020 07" message="There is a cat in the house"

请注意,这会将任何 key: value 对转换为 key="value",前提是 : 字符仅用于指定 key 而不用于其他任何用途。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 2015-12-29
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多