簡體   English   中英

sed 僅在與模式不匹配的行中用 ' 替換 " 的命令

[英]sed command to replace " with ' only in lines that doesn't match a pattern

我的文字如下所示:

“測試”文件:

123,James,123,"
hello "X"
this is a "string", cool.
another "string", here.
",7

我的目標:在所有與模式[^number,string,number][^",number]不匹配的行中,將"替換為'

意思是,輸出應該是這樣的:

123,James,123,"
hello 'X'
this is a 'string', cool.
another 'string', here.
",7

到目前為止,我的 sed 命令是:

sed '/\(^[0-9]*,.*,[0-9]*\|^",[0-9]\)/!s/"/'/g' test

我的問題出在替代部分,我試圖逃脫但它不允許我,而且我似乎無法找到解決方案。 例如,如果我嘗試用#切換' ,它會起作用。 我試過: ...!s/"/\'/g'但它不起作用。

會喜歡你的幫助! 謝謝!

[已解決]:對於那些也有這個問題的人,我將打開的paranthese切換為"並且也逃脫了!解決方案:

sed "/\(^[0-9]*,.*,[0-9]*\|^\",[0-9]\)/\!s/\"/'/g"

使用您顯示的示例,請嘗試使用以下awk代碼。 在 GNU awk中編寫和測試應該適用於任何awk版本。

awk '!/^"/ && !/^[0-9]+.*[a-zA-Z]+[0-9]+/{gsub(/"/,"\047")} 1' Input_file

使用sed

$ sed -E '/^(",)?[0-9]+($|,[[:alpha:]]+,[0-9])/!s/"/'"'"'/g' input_file
123,James,123,"
hello 'X'
this is a 'string', cool.
another 'string', here.
",7

您可以使用sed -E這樣就不必轉義括號。

注意:

  • 如果您使用[0-9]* ,您將匹配可選數字, [0-9]+匹配 1 個或多個數字。
  • 對於string部分,您使用.*但匹配整行

例如

sed -E "/(^[0-9]+,.*,[0-9]|^\",[0-9])/!s/\"/'/g" test

使用awk ,如果例如在第一次檢查中只能有 2 個逗號:

awk '!/^(",[0-9]|[0-9]+,[^,]*,[0-9])/{gsub(/"/,"\047")}1' test

兩者都將 output:

123,James,123,"
hello 'X'
this is a 'string', cool.
another 'string', here.
",7

這可能對你有用(GNU sed):

sed -E '/^("|[0-9]+,[^,]+),[0-9]+/!y/"/'\''/' file

如果該行與所需的字符串不匹配,則將所有"的轉換為'的。

注意成語'\''在 shell 中打了一個洞,然后\'引用了單引號。

暫無
暫無

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

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