0

I have file called foo.txt. This file contains values:

abc.tar.gz
abc.1.1.tar.gz
bca-1.2.tar.gz

I would like to get an output like this

abc abc.tar.gz
abc.1.1 abc.1.1.tar.gz
bca-1.2 bca-1.2.tar.gz

Same value/text has to appear before original value/text. How to achieve this using regular expressions?

%s/^[a-z_-]*./\1/g

Above expression I used but I got wrong output.

  • Does each line really start with four spaces? – Sparhawk Sep 20 '18 at 11:53
  • @Sparhawk no start with characters only – shas Sep 20 '18 at 11:58
5

Capture groups :help /\( let you store what's matched by the pattern inside \(...\); you can then reference the match (via \1 for the first group, \2, and so on) in the replacement (or even afterwards in the pattern itself).

One approach (there are many) to your problem is to capture the filename before the .tar.gz extension. In the replacement, put the capture (\1), a space, then the original text (\0, or &):

:%substitute/\(.*\)\.tar\.gz$/\1 &/

Alternatively, you can just match the stuff before the extension (ending the match with \ze), and then duplicate that:

:%substitute/.*\ze\.tar\.gz$/& &/

Problems with your attempt

  • You used the backreference \1, but never captured anything.
  • The [a-z_-] does not match a literal ., but this appears in your example.
  • No escaping of the final . (as \.); it would match any character.
  • No duplication in the replacement part; you effectively removed text instead of adding.
0

If it's always .tar.gz to be removed, then:

%s/^\(.*\).tar.gz/\1 \1.tar.gz/g
0

filename: testt

abc.tar.gz
abc.1.1.tar.gz
bca-1.2.tar.gz

command

sed "s/[a-z]\{3\}\.\{0,1\}-\{0,2\}\.\{0,1\}[0-9]\{0,1\}\.\{0,1\}[0-9]\{0,1\}/& &/" test| sed "/[a-z]\{3\}\. /s/\.//1"

output

abc abc.tar.gz
abc.1.1 abc.1.1.tar.gz
bca-1.2 bca-1.2.tar.gz
-2

Does it have to be vi?

If not, this might do what you want.

cat foo.txt | xargs -i basename {} .tar.gz | xargs -i echo {} {}.tar.gz

where foo.txt is your file.

Update.

$ cat foo.txt
abc.tar.gz
abc.1.1.tar.gz
bca-1.2.tar.gz


$ cat foo.txt | xargs -i basename {} .tar.gz | xargs -i echo {} {}.tar.gz
abc abc.tar.gz
abc.1.1 abc.1.1.tar.gz
bca-1.2 bca-1.2.tar.gz

You dont get it as above?

  • abc.tar.gz.tar.gzabc.tar.gz.tar.gz.tar.gz output was like that – shas Sep 20 '18 at 11:38
  • space was not applied correctly, it works – shas Sep 20 '18 at 12:13
  • Bloody hell...I got negged twice... was just trying to help :-) and it worked too. – chai Sep 20 '18 at 13:14

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.