修复此文件的 sed 命令是什么,以便将倒数第二个布尔值转换为相反的

修复此文件的 sed 命令是什么,以便将倒数第二个布尔值转换为相反的

给出一个包含如下文本行的文件

"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",然后进行相应的替换。

相关内容