shantanuo
shantanuo

Reputation: 32306

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 must be a better way.

Upvotes: 4

Views: 1200

Answers (3)

kurumi
kurumi

Reputation: 25599

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

Upvotes: 0

Dennis Williamson
Dennis Williamson

Reputation: 359965

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/"$//'

Upvotes: 3

bmk
bmk

Reputation: 14137

Maybe you prefer something like this:

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

Upvotes: 2

Related Questions