[英]How to remove special characters like a single quote from a string?
我嘗試使用Sed,但是沒有成功。 基本上,我有一個字符串說:
輸入:
'http://www.google.com/photos'
需要的輸出:-
http://www.google.com
我嘗試使用sed,但無法轉義'。 我所做的是:-sed's / \\'//'| sed's / photos //'
sed的照片可以用,但不能用。 請提出解決方案。
在sed轉義“ 通過一個解決方法 是可能的:
sed 's/'"'"'//g'
# |^^^+--- bash string with the single quote inside
# | '--- return to sed string
# '------- leave sed string and go to bash
但是對於這項工作,您應該使用tr:
tr -d "'"
Perl替換的語法與sed相同,比sed更好,默認情況下幾乎在每個系統中都安裝了Perl替換項,並且以相同的方式(可移植性)在所有機器上工作:
$ echo "'http://www.google.com/photos'" |perl -pe "s#\'##g;s#(.*//.*/)(.*$)#\1#g"
http://www.google.com/
請注意,此解決方案將僅保留域名開頭的域名,而丟棄http://www.google.com/之后的所有單詞
如果要使用sed進行操作,則可以按照WiktorStribiżew在評論中的建議使用sed“ s /'// g”。
PS:我有時會按照man ascii
建議,用特殊字符的ascii十六進制代碼來引用特殊字符,即\\x27
表示'
因此,對於sed,您可以執行以下操作:
$ echo "'http://www.google.com/photos'" |sed -r "s#'##g; s#(.*//.*/)(.*$)#\1#g;"
http://www.google.com/
# sed "s#\x27##g' will also remove the single quote using hex ascii code.
$ echo "'http://www.google.com/photos'" |sed -r "s#'##g; s#(.*//.*)(/.*$)#\1#g;"
http://www.google.com #Without the last slash
如果您的字符串存儲在變量中,則可以使用純bash來實現上述操作,而無需使用諸如sed或perl這樣的外部工具,例如:
$ a="'http://www.google.com/photos'" && a="${a:1:-1}" && echo "$a"
http://www.google.com/photos
# This removes 1st and last char of the variable , whatever this char is.
$ a="'http://www.google.com/photos'" && a="${a:1:-1}" && echo "${a%/*}"
http://www.google.com
#This deletes every char from the end of the string up to the first found slash /.
#If you need the last slash you can just add it to the echo manually like echo "${a%/*}/" -->http://www.google.com/
尚不清楚'
是否實際上在您的字符串周圍,盡管這需要注意:
str="'http://www.google.com/photos'"
echo "$str" | sed s/\'//g | sed 's/\/photos//g'
合並:
echo "$str" | sed -e "s/'//g" -e 's/\/photos//g'
使用tr
:
echo "$str" | sed -e "s/\/photos//g" | tr -d \'
結果 :
http://www.google.com
如果單引號不在您的字符串中,則無論如何它都應該起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.