我有一個 bash 腳本,我想在所有下劃線前添加一個反斜杠。該腳本搜索目錄中的所有檔案并將檔案名保存到變數file中。然后在變數中我想用 替換每個_實體\_。
我已經查看了關于 sed 的幾個關于搜索和替換以及如何處理特殊字符的問題,但它們似乎都不適用于這種情況。
#!/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/_/\_/}
看來我需要逃避反斜杠。但是,如果我這樣做,我可以獲得反斜杠但沒有下劃線。我還嘗試在下劃線之前簡單地插入反斜杠,但這也有問題。
uj5u.com熱心網友回復:
簡單而明顯的解決方案是在引數擴展中轉義或參考反斜杠。
你的斜線也錯了;您的嘗試只會用文字 string 替換第一個\_/。
回顧一下,語法是${variable/pattern/replacement}替換第一次出現的pattern,并${variable//pattern/replacement}替換所有出現的。
fileWithEscapedUnderscores=${file//_/\\_}
# or
fileWithEscapedUnderscores=${file//_/'\_'}
您的第一次sed嘗試也應該奏效;但當您可以使用 shell 內置時,請避免呼叫外部行程。
另外,可能要注意在帶有檔案名的變數周圍使用引號,盡管在您的示例中并不重要;另請參閱何時在 shell 變數周圍加上引號
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/420380.html
標籤:
