0

I have a big file that contains among others serveral lines of the following form:

USet07-1
USet07-2
USet08-1
USet08-2
.
.
.
USet22-2
.
.
.

I want to remove the hyphen/dash - from these strings in vim. I search for the strings with:

:/USet\d\d-\d

but when I try to replace these with

:%s/Uset\d\d-\d/USet\d\d\d

I obviously get

USetddd

for all instances. But what I want is:

USet071
USet072
USet081
USet082
.
.
.
USet222
.
.
.

How can this be done? Can I reuse parts of the matched string and use it in the substitution?

4

Yes you can, with capture groups. Basically, you wrap the parts of the pattern with \(...\) and reference that in the replacement part with \1 etc.:

:%s/Uset\(\d\d\)-\(\d\)/USet\1\2

Since you only want to remove a single part of the pattern, a shorter option is restricting the actual match (but still asserting that the stuff around is also there) via \zs (match start) and \ze (match end):

:%s/Uset\d\d\zs-\ze\d//

These are all very basic things, and capture groups are common in many regular expression-based tools (like sed). Learn how to look up commands and navigate the built-in :help; it is comprehensive and offers many tips. You won't learn Vim as fast as other editors, but if you commit to continuous learning, it'll prove a very powerful and efficient editor.

1

I found a solution myself using substring matching thanks to the vim help:

:%s/\(USet\d\d\)-\(\d\)/\1\2/gc
0
Using sed command

sed "/^USet/s/-//" filename >outputfile

Suppose if you want to perform on orginal file

sed -i "/^USet/s/-//" filename

output

USet071
USet072
USet081
USet082

awk command

awk '/^USe/{sub("-","",$0);print }' filename >outfile

output

USet071
USet072
USet081
USet082
0

The regex can be easier to work with if you use the \v pattern prefix. With that, you don't have to escape (, {, [ and more.

:%s/\vUSet(\d\d)-(\d)/USet\1\2/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.