2017-03-05 90 views
0

使用Sed我試過了,但沒有成功。 基本上,我有一個字符串說: -如何從字符串中刪除特殊字符,如單引號?

輸入: - 需要

'http://www.google.com/photos'

輸出: -

http://www.google.com

我試着使用SED但逃脫'是不可能的。 我做的是: - sed's/\'//'| sed's/photos //'

sed的照片工作,但'它沒有。 請建議可以解決什麼問題。

+2

儘量'sed的「S /'// G」' –

+0

@GeorgeVasiliou:請參閱http://ideone.com/pSmb3l –

回答

-1

目前還不清楚如果'實際上是在你的字符串,雖然這應該照顧它:

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 

如果單引號不在你的字符串周圍,它應該工作不管。

0

在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 "'" 
0

Perl的更換有語法相同的sed,比sed工作得更好,默認情況下幾乎安裝在每個系統中,並以相同方式適用於所有機器(便攜性):

$ echo "'http://www.google.com/photos'" |perl -pe "s#\'##g;s#(.*//.*/)(.*$)#\1#g" 
http://www.google.com/ 

記住,這個解決方案將只保留域名與前面的http,丟棄所有的字下面http://www.google.com/

如果你想與SED這樣做,你可以使用SED「S /'// G」正如WiktorStribiżew在評論中所建議的那樣。
PS:我有時把特殊字符與特殊字符的它們的ASCII十六進制代碼由man 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/ 
相關問題