如何转义从文件获取的内容中的双引号

如何转义从文件获取的内容中的双引号

statusfile.log我在从到添加内容时尝试转义双引号statusfile_truncated.log

我四处寻找,但越来越困惑。您将如何实现它?

这是我目前得到的:

#!/bin/bash

statusfile="statusfile.log"
statusfile_truncated="statusfile_truncated.log"
tail -n 50 $statusfile >> $statusfile_truncated

statusfile.log的内容:

2017-05-15 22:36:18 test.somedomain.com <--- 250 CWD successful. "/xxxxxxxxxxxxx" is current directory.
2017-05-15 22:36:18 test.somedomain.com <--- 250 CWD successful. "/xxxxxxxxxxxxx" is current directory.
2017-05-15 22:36:18 test.somedomain.com <--- 250 CWD successful. "/xxxxxxxxxxxxx" is current directory.

statusfile_truncated.log 的内容应该是:

2017-05-15 22:36:18 test.somedomain.com <--- 250 CWD successful. \"/xxxxxxxxxxxxx\" is current directory.
2017-05-15 22:36:18 test.somedomain.com <--- 250 CWD successful. \"/xxxxxxxxxxxxx\" is current directory.
2017-05-15 22:36:18 test.somedomain.com <--- 250 CWD successful. \"/xxxxxxxxxxxxx\" is current directory.

答案1

如果您只想在双引号前插入一个反斜杠,您可以sed这样做:

sed 's/"/\\"/g' $statusfile >> $statusfile_truncated

但如果要真正逃脱,还应该考虑其他工具和技术。

答案2

引用字符串的最佳方式bash是使用%b选项 in printf。这将处理所有特殊字符:

$ variablename='foo "bar and C:\\foo\\bar'
$ printf '%b\n' "$variablename"
foo "bar and C:\foo\bar

相关内容