0

I have a file with data that goes like this.

Engine1
Temp:10
Humidity:23 
Engine1
Temp:13
Humidity:21 
Engine2
Temp:10
Humidity:23

This pattern repeats throughout the file. I want to do the following in a single vim command.

  1. Search for Engine1
  2. Copy the line that has the pattern Engine1
  3. Copy the next 2 lines (which has the data related to it)
  4. Output the results to a new file

This command needs to do this for the whole file wherever this pattern appears.

2
  • You can use let @c=''|:g/engine1/1,3y C then in the new file "cP will paste the match. regular expression deletion will help. Depending on what you mean by file :h :redir may assist
    – Steve
    Jan 4 at 23:27
  • This is the command I was looking for :g/Engine1/.,.+2w! >> Newfile.txt
    – Explorer
    Jan 5 at 14:55
1

EDITED:

You can use this:

:g/Engine1/.,.+2w! >> Newfile.txt

It will find all the occurence of Engine1 and copy his line with the two line below to the file Newfile.txt

You can also create a personnal command:

:command -nargs=1 MySearch :g/<args>/.,.+2w! >> file.txt

After entering this command, if you try writting :MySearch Engine1 It will do the same things but you can change your key (Engine2, Engine3, etc.)

More details

  • :g means global find all the lines conaining a pattern and execut a command for each of them :global/pattern/command (see :help :global)
  • :w means write write the content of the actual buffer to a file - :write file(see :help :write)
  • :command create a user-custom command (see :help command)
9
  • 3
    I think you would want to append rather than overwrite to the file. so you should probably use :g.../.,.+2w >> newfile.txt Jan 5 at 8:58
  • Good Idea! It can help this way. I will edit my answer. Jan 5 at 10:56
  • 2
    Note that :g abbreviates :global and :w! abbreviates :write! (I find myself among a minority that prefers longhand in scripts and answers; shorthands are reserved for interactive use)
    – D. Ben Knoble
    Jan 5 at 13:45
  • @ChristianBrabandt That worked!
    – Explorer
    Jan 5 at 14:55
  • 1
    Note that you don't actually need the dots at all... :g/Engine1/,+2w >>file.txt works just as well. You don't need :w! either, just :w will do since you're appending.
    – filbranden
    Jan 5 at 17:31

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.