sed replace two double quotes and keep text

2019-07-22 11:21发布

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,

标签: bash sed replace
7条回答
爷、活的狠高调
2楼-- · 2019-07-22 12:01

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.

查看更多
SAY GOODBYE
3楼-- · 2019-07-22 12:03

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.

查看更多
Root(大扎)
4楼-- · 2019-07-22 12:13
$ sed 's/"\("[^"]*"\)"/\1/' file
"text"
"text"
""
查看更多
走好不送
5楼-- · 2019-07-22 12:14

Could you please try following awk command and let me know if this helps you.

awk -v s1="\"" '!/^\"\"$/{gsub(/\"\"/,s1)} 1'  Input_file
查看更多
狗以群分
6楼-- · 2019-07-22 12:14

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楼-- · 2019-07-22 12:15
echo -e '""text""\n"text"\n""' |awk '/""text""/{gsub(/""/,"\42")}1'

"text"
"text"
""
查看更多
登录 后发表回答