sed 或 awk 从文本文件中删除 (,)

发布于 2024-10-26 20:12:35 字数 218 浏览 0 评论 0原文

这是我的场景。文本文件看起来像这样

"1","2,c","3","4,a","7"
"8","9,c","4","6,d","9"

,所以我想要的是将 (,) 替换为 (-)

ex - 而不是 "2,c" 为 "2-c" 我只需要更改 "" 内的逗号而不是其他逗号分隔用于 csv 文件。这应该在全球范围内改变

谢谢!!

here the scenarios I have. the text file looks like this

"1","2,c","3","4,a","7"
"8","9,c","4","6,d","9"

so what I want is replace (,) with (-)

ex - instead of "2,c" to be "2-c" I only need the comma inside "" to be change not other comma separated used for csv file. this should change globally

Thanks!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梨涡 2024-11-02 20:12:35

s#([^"]),([^"])#\1-\2#g 适用于您的示例:

$ cat example 
"1","2,c","3","4,a","7"
"8","9,c","4","6,d","9"
$ sed -E -e 's#([^"]),([^"])#\1-\2#g' example
"1","2-c","3","4-a","7"
"8","9-c","4","6-d","9"

sed 表达式分解为“替换所有 , 字符不在两个 " 字符与 - 字符之间"

编辑:OP 的 sed 不支持扩展(现代)常规。表达式,所以这是一个 BRE 的示例:

$ sed -e 's#\([^"]\),\([^"]\)#\1-\2#g' example
"1","2-c","3","4-a","7"
"8","9-c","4","6-d","9"

s#([^"]),([^"])#\1-\2#g works on your example:

$ cat example 
"1","2,c","3","4,a","7"
"8","9,c","4","6,d","9"
$ sed -E -e 's#([^"]),([^"])#\1-\2#g' example
"1","2-c","3","4-a","7"
"8","9-c","4","6-d","9"

The sed expression breaks down as "replace all , characters that aren't between two " characters with - characters".

Edit: OP's sed doesn't support extended (modern) regular expressions, so here's an example with a BRE:

$ sed -e 's#\([^"]\),\([^"]\)#\1-\2#g' example
"1","2-c","3","4-a","7"
"8","9-c","4","6-d","9"
半城柳色半声笛 2024-11-02 20:12:35

我已经做了很多全局替换并且有一个替代方案,你可能只是让这里的生活变得太复杂了。如果您使用 emacs 编辑器,您只需执行三个全局替换语句:

Mx repl -s "," "--" 将 "," 替换为唯一的字符串,然后
Mx repl-s ' 其中您将所有剩余的 ' 替换为空格,然后您只需将另一个逗号放回

Mx repl-s "--" "," 我知道这不是严格意义上的 sed 示例,但我认为它可能提供一个不错的选择。有时我更喜欢直接跳入文本编辑器,而不是把所有东西都整理好,但这可能只是我的情况。

I have done alot of global replaces and have an alternative,you might just be making life too complicated here. If you use the emacs editor you can just do three global replace statements:

M-x repl-s "," "--" replace the "," with a unique string, then just
M-x repl-s ' where you replace all remaining ' with a space, then you just put the other comma's back with

M-x repl-s "--" "," I know this isn't strictly a sed example but I thought it might provide a nice alternative. I sometimes prefer to just hop in a text editor rather than sed-ing everything up, but that might just be me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文