问题
Text to be processed :
""text""
"text"
""
output desired :
"text"
"text"
""
Tried with :
echo -e '""text""\n"text"\n""' | sed -e 's/"".*""/".*"/g'
But obviously no luck.
Cheers,
回答1:
You want to use a backreference (something that refers to a previously matched part) in your sed command :
echo -e '""text""\n"text"\n""' | sed -E -e 's/""(.*)""/"\1"/g'
Here are the modifications I did :
- I grouped what was inside the double-quote in the matching pattern with
(...)
- I referenced that matching group in the replacement pattern with
\1
- I told sed to use
-E
xtended regex so I wouldn't have to escape the grouping parenthesis
回答2:
Based on your sample input, you could just use this:
sed '/^""$/! s/""/"/g' file
On lines which don't only contain two double quotes, globally replace all pairs of double quotes with one double quote.
回答3:
$ sed 's/"\("[^"]*"\)"/\1/' file
"text"
"text"
""
回答4:
Could you please try following awk command and let me know if this helps you.
awk -v s1="\"" '!/^\"\"$/{gsub(/\"\"/,s1)} 1' Input_file
回答5:
Another approach
cat file | sed 's/"//g' | sed 's/^/"/g' | sed 's/$/"/g'
Details
sed 's/"//g'
remove all double quote
sed 's/^/"/g'
put a double quote at the beginning of each line
sed 's/$/"/g'
put a double quote at the end of each line
Note
This approach will work only if there is one word per line, like in your example.
回答6:
Answer by Aaron is also fine but back-referencing is costlier in general. Why not use a simpler command:
echo -e '""text""\n"text"\n""' | sed 's/""*/"/g'
Regex to replace more than one double quote to single one.
回答7:
echo -e '""text""\n"text"\n""' |awk '/""text""/{gsub(/""/,"\42")}1'
"text"
"text"
""
来源:https://stackoverflow.com/questions/46488778/sed-replace-two-double-quotes-and-keep-text