循环打印时双反斜杠消失

循环打印时双反斜杠消失

我有一个脚本将各种数据字段列表连接在一起,然后需要添加更多列。生成的文件如下所示:

$ cat compiled.csv
"name":"Network Rule 1", "description":"Network Rule 1", "from":["internal"], "source":["any"], "user":["domain\\network_user1"], "to":["external"], "destination":["host.example.com","10.1.2.1"], "port":["8443","22"],
"name":"Network Rule 2", "description":"Network Rule 2", "from":["internal"], "source":["any"], "user":["domain\\network_user2"], "to":["external"], "destination":["host.example.com","10.2.1.1"], "port":["23","25"],
"name":"Network Rule 3", "description":"Network Rule 3", "from":["internal"], "source":["any"], "user":["domain\\network_user3"], "to":["external"], "destination":["host.example.com","10.3.4.1"], "port":["80","143"],

我正在尝试将更多字段(都相同)添加到列表中;这些字段就像......

“访问”:“允许”,“时间”:“00:00:00-23:59:59”,“通知”:“是”

最终输出应如下所示:

"name":"Network Rule 1", "description":"Network Rule 1", "from":["internal"], "source":["any"], "user":["domain\\network_user1"], "to":["external"], "destination":["host.example.com","10.1.2.1"], "port":["8443","22"], "access":"allow", "time":"00:00:00-23:59:59", "notify":"yes"
"name":"Network Rule 2", "description":"Network Rule 2", "from":["internal"], "source":["any"], "user":["domain\\network_user2"], "to":["external"], "destination":["host.example.com","10.2.1.1"], "port":["23","25"], "access":"allow", "time":"00:00:00-23:59:59", "notify":"yes"
"name":"Network Rule 3", "description":"Network Rule 3", "from":["internal"], "source":["any"], "user":["domain\\network_user3"], "to":["external"], "destination":["host.example.com","10.3.4.1"], "port":["80","143"], "access":"allow", "time":"00:00:00-23:59:59", "notify":"yes"

当我尝试在循环中附加字段时,在脚本中和直接在 shell 中运行以下命令时,双反斜杠都会消失。

while read LINE; do
 echo $LINE \"access\":\"allow\", \"time\":\"00:00:00-23:59:59\", \"notify\":\"yes\"
done < compiled.csv > completed_list.csv

相反,这会导致以下示例中用户名双反斜杠消失。

"name":"网络规则 1", "description":"网络规则 1", "from":["internal"], "source":["any"],“用户”:[“域\network_user1”], "to":["external"], "destination":["host.example.com","10.1.2.1"], "port":["8443","22"], "access":"允许", "时间":"00:00:00-23:59:59", "通知":"是"

我猜使用 echo 打印整行有问题,但是有什么办法可以解决这个问题呢?

先感谢您。

答案1

read默认情况下,解释可用于从定界中转义 IFS 字符的反斜杠,该-r选项将其关闭。

$ read a b  <<< '1\ 2 3'
$ printf "<%s>\n" "$a"
<1 2>
$ read -r a b  <<< '1\ 2 3'
$ printf "<%s>\n" "$a"
<1\>

另外,即使只给出一个变量名,read也会删除前导和尾随空格(如果存在于 IFS 中),因此您可能需要将 IFS 显式设置为空字符串,以获得未经修改的输入行。

根据您的 shell 和设置,echo可以打印时处理反斜杠。更好地使用printf "%s\n" "..."

另外,如果打印双引号,则用单引号引用整个字符串可能会更容易,而不是单独转义每个字符串。

所以,也许:

while IFS= read -r LINE; do
    echo "$LINE"' "access":"allow", "time":"00:00:00-23:59:59", "notify":"yes"'
done < compiled.csv > completed_list.csv

话又说回来,由于看起来您只是在每行末尾添加一个固定字符串,因此您可以使用 sed 代替。它可能会比 shell 更快:

sed -e 's/$/ "access":"allow", "time":"00:00:00-23:59:59", "notify":"yes"/' < compiled.csv > completed_list.csv

相关内容