我正在使用 bash shell。我有一個僅包含該行的文本檔案
name "Test Program"
我想在名稱后的字串周圍添加花括號,使檔案看起來像
name { “Test Program" }
我試過下面的表達
perl -pi -e 's/name(\s )"(.*)"/name$1{ "$2" }/g' /tmp/test.txt
但最終得到的檔案只包含
name
我對任意空格(\ s)或替換有誤解嗎?
uj5u.com熱心網友回復:
perl -pi -e 's/name(\s )"(.*)"/name$1{ "$2" }/g' /tmp/test.txt
在這里,$1{ "$2" }被解釋為“散列的$2鍵%1”。
在$1變數周圍放置大括號以消除擴展的歧義:
perl -pi -e 's/name(\s )"(.*)"/name${1}{ "$2" }/g' /tmp/test.txt
# ..................................^.^
或逃避開放大括號
perl -pi -e 's/name(\s )"(.*)"/name$1\{ "$2" }/g' /tmp/test.txt
# ...................................^
或者,使用\K運算子
perl -pi e 's/name\s \K(".*")/{ $1 }/' test.txt
uj5u.com熱心網友回復:
假設只有一對雙引號,而不限于perl解決方案......
一個想法使用sed:
sed -E 's/("[^"]*")/{ \1 }/' test.txt
在哪里:
-E- 啟用擴展正則運算式(和捕獲組)("[^"]*")- (捕獲組)匹配一個"0 個或多個non-"字符"{ \1 }- 將匹配替換為{捕獲組}
這會產生:
name { "Test Program" }
一旦滿意結果正確,您可以添加-i標志以對源檔案進行更改,例如:
$ cat test.txt
name "Test Program"
$ sed -Ei 's/("[^"]*")/{ \1 }/' test.txt
$ cat test.txt
name { "Test Program" }
假設我們需要驗證name字串的匹配......
sed -E 's/([[:space:]]*name[[:space:]] )("[^"]*")/\1{ \2 }/' test.txt
在哪里:
([[:space:]]*name[[:space:]] )-(第一個捕獲組)是 0 個或多個空格name1 個或多個空格("[^"]*")-(第二個捕獲組)與之前相同的解釋\1{ \2 }- 第一個捕獲組{第二個捕獲組}
示例資料檔案:
$ cat test.txt
name "Test Program"
name "Test Program"
boat "Test Program"
names "Test Program"
$ sed -E 's/([[:space:]]*name[[:space:]] )("[^"]*")/\1{ \2 }/' test.txt
name { "Test Program" }
name { "Test Program" }
boat "Test Program"
names "Test Program"
uj5u.com熱心網友回復:
用 sed 試試:
cat test.txt | sed 's/^name[ ]\ /name { /g' | sed 's/["][ ]*$/" }/g'
uj5u.com熱心網友回復:
你可以使用這個perl命令:
perl -i -pe 's/(name\s )("[^"] ")/$1 { $2 }/' file
cat file
name { "Test Program" }
或者這個sed:
sed -i.bak -E 's/(name[[:blank:]] )("[^"] ")/\1 { \2 }/' file
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/371909.html
上一篇:用perl替換多個檔案中除第一個匹配項之外的所有匹配項
下一篇:Perl字串-替換多個字符
