删除 Vim 中的重复行? [英] Remove Duplicate Line in Vim?

查看:42
本文介绍了删除 Vim 中的重复行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 VIM 删除我创建的 XML 文件中的重复行.(我无法重新创建文件,因为 ID 号会改变.)

I'm trying to use VIM to remove a duplicate line in an XML file I created. (I can't recreate the file because the ID numbers will change.)

文件看起来像这样:

    <tag k="natural" v="water"/>
    <tag k="nhd:fcode" v="39004"/>
    <tag k="natural" v="water"/>

我正在尝试删除重复的 k="natural" v="water" 行之一.当我尝试使用 \_ 修饰符在我的正则表达式替换中包含换行符时,VIM 似乎没有找到任何东西.

I'm trying to remove one of the duplicate k="natural" v="water" lines. When I try to use the \_ modifier to include newlines in my regex replaces, VIM doesn't seem to find anything.

关于使用什么正则表达式或工具的任何提示?

Any tips on what regex or tool to use?

推荐答案

首先,你可以使用 awk 删除所有重复的行,保持它们的顺序.

First of all, you can use awk to remove all duplicate lines, keeping their order.

:%!awk '\!_[$0]++'

如果您不确定是否还有其他一些不想删除的重复行,那么只需添加条件即可.

If you not sure if there are some other duplicate lines you don't want remove, then just add conditions.

:%!awk '\!(_[$0]++ && /tag/ && /natural/ && /water/)'

但是,恕我直言,用正则表达式解析像 xml 这样的嵌套结构是个坏主意.你会关心他们不要一直被搞砸.xmllint 为您提供文件中特定元素的列表:

But, parsing a nested structure like xml with regex is a bad idea, IMHO. You are going to care them not to be screwed up all the time. xmllint gives you a list of specific elements in the file:

:!echo "cat //tag[@k='natural' and @v='water']" | xmllint --shell %

您可以逐步删除重复的行.

You can slash duplicate lines step by step.

这篇关于删除 Vim 中的重复行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆