使用 bash 脚本将下划线替换为反斜杠和下划线

Using bash script to replace underscore with a backslash and underscore

我有一个 bash 脚本,我想在所有下划线前添加一个反斜杠。该脚本搜索目录中的所有文件并将文件名保存到变量file。然后在变量中我想用 \_.

替换 _ 的每个实例

我查看了 sed 上关于搜索和替换以及如何处理特殊字符的几个问题,但其中 none 似乎正确适用于这种情况。

#!/bin/bash
file=some_file_name.f90 # I want this to read as some\_file\_name.f90
# I have tried the following (and some more i didnt keep track of)
fileWithEscapedUnderscores=$(sed 's/_/\_/g' <<<$file)
fileWithEscapedUnderscores=$(sed 's/_/\_/g' <<<$file)
fileWithEscapedUnderscores=$(sed 's/_/\\_/g' <<<$file)
fileWithEscapedUnderscores=${file/_/\_/}

看来我需要转义反斜杠。但是,如果我这样做,我可以获得反斜杠但没有下划线。我也试过在下划线前简单地插入一个反斜杠,但也有问题。

简单明了的解决方案是在参数扩展中转义或引用反斜杠。

你的斜杠也错了;您的尝试只会用文字字符串 \_/.

替换第一个

回顾一下,语法是 ${variable/pattern/replacement} 替换第一次出现的 pattern${variable//pattern/replacement} 替换所有出现的地方。

fileWithEscapedUnderscores=${file//_/\_}
# or
fileWithEscapedUnderscores=${file//_/'\_'}

您的第一次 sed 尝试应该也成功了;但是当你可以使用 shell 内置函数时,避免调用外部进程。

另外,可能要注意在带有文件名的变量周围使用引号,尽管在您的示例中这无关紧要;另见 When to wrap quotes around a shell variable