Crop text using sed

How to remove first and last quotes?

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

The above works as expected, but I think there should be a better way.

+4
source share
3 answers

You can combine sed calls in one:

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

The command you sent will delete the first quote, even if it is not at the beginning of the line. If you want to make sure that this is done only at the beginning, you can bind it like this:

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

Some versions of sed do not like several commands separated by semicolons. You can do this for them (it also works in those that accept semicolons):

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

Perhaps you prefer something like this:

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

if you are sure that there are no quotes other than the first and last, just use the /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 

Pay attention to the second example of the first and last quotes, which may not be exactly in the first and last positions.

example with a lot of 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
source

Source: https://habr.com/ru/post/1344239/


All Articles