1

There is a text file like that

root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/bin/false

daemon:x:2:2:daemon:/sbin:/bin/false
mail:x:8:12:mail:/var/spool/mail:/bin/false
ftp:x:14:11:ftp:/srv/ftp:/bin/false
http:x:33:33:http:/srv/http:/bin/false

How to replace in VI all characters in strings 2-4 from 2nd to 5th to 'X'?

UPD: it's smth like: :2,4s//X/g I guess I need a regular expression

UPD2: :2,4s/^\(.\)...\|^$/\1XXX/ | 2,4s/^$/ XXX/

Trionia
  • 127
  • 1
  • 9

1 Answers1

1

Vim only

Try this command:

:2,4s/\%2c.../XXX/

Where:

  • 2,4 is for in strings 2-4
  • \%2c... is for from 2nd to 5th
  • XXX is for to 'X'

Both Vim and Vi

As Vi doesn't have \%c, this command should be used instead:

:2,4s/^\(.\).../\1XXX/

Resources

xaizek
  • 5,098
  • 1
  • 34
  • 60
  • Substitute pattern match failed. Thanx for reference – Trionia Dec 27 '13 at 07:51
  • Are you using vim or vi? vi doesn't have `\%c`. How about this command: `:2,4s/^\(.\).../\1XXX/`? – xaizek Dec 27 '13 at 07:54
  • How can I change regular expression so it will not ignore empty strings? – Trionia Dec 27 '13 at 08:33
  • You can add `\|^$`, but it won't insert any character at first column. I think applying two substitutions in a row would be a better choice (the second one could look like `:2,4s/^$/ XXX/`). – xaizek Dec 27 '13 at 08:38
  • The thing is to do this in one command. Explain please how to add this `\|^$` – Trionia Dec 27 '13 at 08:58
  • Just add it to regular expression, like this: `:2,4s/^\(.\)...\|^$/\1XXX/`. – xaizek Dec 27 '13 at 08:59
  • vi probably doesn't like that there is no capture in the second regular expression, maybe `:2,4s/^\(.\)...\|^\(\)$/\1XXX/` will work. – xaizek Dec 27 '13 at 09:35
  • 1
    I've tried it different ways and concluded that vi doesn't understand "OR" expression in this case. So you was right, two substitutions in a row will be good solution. I used the following expression `:2,4s/^\(.\)...\|^$/\1XXX/ | 2,4s/^$/ XXX/` – Trionia Dec 28 '13 at 10:53