简体   繁体   中英

Find and replace strings using sed

I am trying to replace strings in a document that enclosed in single quotes, to a string without.

'test' -> test

Is there a way using sed I can do this?

Thanks

This will remove single quotes from around any quoted word, and leave other quotes alone:

sed -E "s/'([a-zA-Z]*)'/\1/g" 

When tested:

foo 'bar' it's 'OK' --> foo bar it's OK

Notice that it left the quote in it's intact.

Explanation:

The search regex '([a-zA-Z]*)' is matching any word (letters, no spaces) surrounded by quotes and using brackets, it captures the word within. The replacement regex \\1 refers to "group 1" - the first captured group (ie the bracketed group in the search pattern - the word)

FYI, here's the test:

echo "foo 'bar' it's 'OK'" | sed -E "s/'([a-zA-Z]*)'/\1/g"

removing single quotes for certain word (text in your example):

kent$  echo "foo'text'000'bar'"|sed "s/'text'/text/g"
footext000'bar'

How about this?

$> cat foo
"test"
"bar"
baz "blub"

"one" "two" three

$> cat foo | sed -e 's/\"//g'
test
bar
baz blub

one two three

Update As you only want to replace "test", it would more likely be:

$> cat foo | sed -e 's/\"test\"/test/g'
test
"bar"
baz "blub"

"one" "two" three

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM