簡體   English   中英

在 Bash 中用雙引號替換單引號

[英]Replace single quotes with double quotes in Bash

我有一個充滿 SAS 標簽文件的目錄。

標簽文件在每個文件中有空格、單引號、空格、單引號:

VAR1 = ' 'SOME LABEL' ' 

我想要一個 bash 腳本,它將用雙引號替換這些單引號,以便我最終得到:

VAR1 = "SOME LABEL"

我怎樣才能做到這一點?

假設我們有這個測試文件:

$ cat file
VAR1 = ' 'SOME LABEL' ' 

要在出現的任何地方用雙引號替換 sinqle-quote-space-single-quote,我們可以使用 sed:

$ sed "s/' '/\"/g" file
VAR1 = "SOME LABEL" 

如果以上產生了您想要的輸出,那么您可能需要就地更改文件。 這可以使用:

sed -i "s/' '/\"/g" file  # linux
sed -i "" "s/' '/\"/g" file  # BSD/OSX

要對當前目錄中的所有文件進行替換:

sed -i "s/' '/\"/g" *  # linux
sed -i "" "s/' '/\"/g" *  # BSD/OSX

例子

$ cat file
VAR1 = ' 'SOME LABEL' '
$ sed -i "s/' '/\"/g" *  # linux
$ cat file
VAR1 = "SOME LABEL" 

我會嘗試類似的東西

for f in *
do
    sed "s/' '/\"/g" "$f" > "$f".new && mv "$f".new "$f"
done

(但是像這樣就地批量編輯文件可能有風險,所以請在嘗試之前備份您的文件!)

例子:

> cat t.sas
variable="vol1"
variable2="vol3"

sed -i '' "s/\"\(.*\)\"/\'\1\'/" *.sas

它的作用是搜索與.sas匹配的目錄中的所有文件,然后在每個文件中搜索正則表達式“ ”,然后將“”替換為 '',同時插入在 sed 命令右側標識的測試。

結果:

> cat t.sas
variable='vol1'
variable2='vol3' 

因此...

sed -i '' "s/\'\(.*\)\'/\"\1\"/" *.sas

> cat t.sas
variable="vol1"
variable2="vol3"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM