开发者

Trim text using sed

How do I remove the first and the last quotes?

echo "\"test\"" | sed 's/"//' | sed 's/"$//'

The above is working as expected, But I guess there mus开发者_运维问答t be a better way.


You can combine the sed calls into one:

echo "\"test\"" | sed 's/"//;s/"$//'

The command you posted will remove the first quote even if it's not at the beginning of the line. If you want to make sure that it's only done if it is at the beginning, then you can anchor it like this:

echo "\"test\"" | sed 's/^"//;s/"$//'

Some versions of sed don't like multiple commands separated by semicolons. For them you can do this (it also works in the ones that accept semicolons):

echo "\"test\"" | sed -e 's/^"//' -e 's/"$//'


Maybe you prefer something like this:

echo '"test"' | sed 's/^"\(.*\)"$/\1/'


if you are sure there are no other quotes besides the first and last, just use /g modifier

$ echo "\"test\"" | sed 's/"//g'
test

If you have Ruby(1.9+)

$ echo $s
blah"te"st"test

$ echo $s | ruby -e 's=gets.split("\"");print "#{s[0]}#{s[1..-2].join("\"")+s[-1]}"'
blahte"sttest

Note the 2nd example the first and last quotes which may not be exactly at the first and last positions.

example with more quotes

$ s='bl"ah"te"st"tes"t'
$ echo $s | ruby -e 's=gets.split("\"");print "#{s[0]}#{s[1..-2].join("\"")+s[-1]}"'
blah"te"st"test
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜