首页 > 解决方案 > 使用 sed 或 awk 转换键值对

问题描述

寻找 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"

标签: regexbashshellawksed

解决方案


使用 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",前提是该:字符仅用于指定 thekey并且没有其他用途。


推荐阅读