1

Given file alfa.txt:

10
11
12
13

I can remove every other line:

$ ex -sc 'g/^/+d' -cx alfa.txt
$ cat alfa.txt
10
12

However I cannot replace every other line:

$ ex -sc 'g/^/+s//> /' -cx alfa.txt
$ cat alfa.txt
10
> 11
> 12
> 13
0
1

Here is a workaround:

ex -sc '%s/\v(.*\n){2}/> &/|x' alfa.txt
  1. % select all lines

  2. s substitute

  3. \v turn on magic

  4. x save and close

5
  • It adds a newline at the end of the file. Also when alfa.txt has 1, 3, 5 , ... lines the last line is ignored since it doesn't match. Apr 18 '16 at 17:10
  • @JairLopez thank you for the comment. Did you have a better solution? Apr 18 '16 at 17:53
  • No. I didn't. But I think your previous workaround was better. As far as I can remember, it was ex -sc 'g/^/s//> /|pu_|j' -cx alfa.txt. The only drawback was the newline at the end. Apr 18 '16 at 18:08
  • @JairLopez yes that is right. However it does not scale. If you wanted every 3 lines, you would need ex -sc 'g/^/s//> /|pu_|j|pu_|j' -cx alfa.txt Apr 18 '16 at 20:16
  • I see. You could try ex -sc '$pu_' -c '%s/\v(.*\n){2}/> &/' -c '$d|x'. In that way it could work when alfa.txt has 1, 3, 5, ... lines, but it still adds a newline at the end of the file. Apr 18 '16 at 20:47

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.