![修复此文件的 sed 命令是什么,以便将倒数第二个布尔值转换为相反的](https://linux22.com/image/1131524/%E4%BF%AE%E5%A4%8D%E6%AD%A4%E6%96%87%E4%BB%B6%E7%9A%84%20sed%20%E5%91%BD%E4%BB%A4%E6%98%AF%E4%BB%80%E4%B9%88%EF%BC%8C%E4%BB%A5%E4%BE%BF%E5%B0%86%E5%80%92%E6%95%B0%E7%AC%AC%E4%BA%8C%E4%B8%AA%E5%B8%83%E5%B0%94%E5%80%BC%E8%BD%AC%E6%8D%A2%E4%B8%BA%E7%9B%B8%E5%8F%8D%E7%9A%84.png)
给出一个包含如下文本行的文件
"00007960-9d81-4192-b548-ad33d6b0ca54","true",0.984725773335,"false",1.0,"true",0.808817088604,"false",0.705779910088,"false",0.928222000599,"false",0.999984204769,"false",1.0,"false",0.904409646988,"true",0.979391694069,"true",0.977430343628,"false",0.999999582767
sed(或类似)命令是什么来修复此文件,以便将每行的倒数第二个布尔值替换为相反的值。因此,对于某些行,值“false”将变为“true”,而对于其他行,值“true”将变为“false”
"00007960-9d81-4192-b548-ad33d6b0ca54","true",0.984725773335,"false",1.0,"true",0.808817088604,"false",0.705779910088,"false",0.928222000599,"false",0.999984204769,"false",1.0,"false",0.904409646988,"true",0.979391694069,"false",0.977430343628,"false",0.999999582767
(注意倒数第二个 true 已经变成 false)
答案1
尝试awk
:
awk -F, 'BEGIN{a["\"true\""] = "\"false\""; a["\"false\""] = "\"true\""; OFS=","} {$(NF - 3) = a[$(NF - 3)]}1'
假设每个记录的倒数第三个字段是"true"
或"false"
。
以下测试倒数第三个字段是否为"true"
或"false"
:
awk -F, 'BEGIN{a["\"true\""] = "\"false\""; a["\"false\""] = "\"true\""; OFS=","} $(NF -3) in a {$(NF - 3) = a[$(NF - 3)]}1'
答案2
和bash
:
#!/bin/bash
while IFS=, read -r -a line; do
if [ "${line[@]:(-4):1}" = \"true\" ]; then
IFS=,; printf '%s\n' "${line[*]:0:$((${#line[@]}-4))},\"false\",${line[*]:(-3)}"
else
IFS=,; printf '%s\n' "${line[*]:0:$((${#line[@]}-4))},\"true\",${line[*]:(-3)}"
fi
done <file.txt
这里我们用每行创建一个数组,元素以 分隔,
。
然后我们检查倒数第四个元素是否是"true"
或"false"
,然后进行相应的替换。