[英]Escaping double quotes within a sed backreference replace
我有以下文字:
Matt has 11 eggs and they are brown
Helen has 23 ducks and they are black and brown
Todd has 34 quarters and they are silver
Bud has 45 pens and they are red, yellow, "greenish" and blue
當我運行以下sed命令時:
sed -E "s/([^ ]+) has ([^ ]+) ([^ ]+) and they are (.*)/\"\1\",\"\2\",\"\3\",\"\4\"/" input
我收到此CSV:
"Matt","11","eggs","brown"
"Helen","23","ducks","black and brown"
"Todd","34","quarters","silver"
"Bud","45","pens","red, yellow, "greenish" and blue"
但是我真正想要的是這個(引號正確轉義):
"Matt","11","eggs","brown"
"Helen","23","ducks","black and brown"
"Todd","34","quarters","silver"
"Bud","45","pens","red, yellow, \"greenish\" and blue"
我該怎么做?
嘗試:
sed -E 's/"/\\"/g;
s/([^ ]+) has ([^ ]+) ([^ ]+) and they are (.*)/"\1","\2","\3","\4"/' input
這首先將所有"
實例替換為\\"
,然后執行原始命令。 請注意,在sed
程序周圍使用單引號會使它更具可讀性。
這可能對您有用(GNU sed):
sed -r 's/"/\\&/g;s/^\\"|\\(",)\\"|\\"$/\1"/g' file
轉換所有"
的,以\\"
的,然后刪除\\
從那些在起點,終點和插圖中的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.