3

I am writing a shell script to view a text file and search for a pattern. I want to specify this pattern in the command line when launching Vim.

This command is what I am currently using do accomplish this:

vim mylogfile.txt +"/findthisvalue" 

The above command works great when the text file contains this pattern. However, if the pattern is not in the file, I want Vim to fail gracefully.

Right now, when it fails to find the pattern in the text file, Vim pops up an error saying the following:

"Error detected while processing command line:
E486: Pattern not found: 01:50:37x
Press ENTER or type command to continue"

Is there a way to tell Vim to just print in the status bar "E486: Pattern not found: findthisvalue" and not display the "Press ENTER to type command to continue"?

What would be the proper command-line to do that?

  • The question is a little unclear, can you explain what you mean by "It work great but then it fails to find a value it halts the loading of the file"? When does it work as you expect exactly? Do you mean that it only happens when you launch Vim with that given command? Also, did you try manually invoking Vim like this and not in a script? – akshay Feb 24 '17 at 2:47
  • @akshay, I edited my question to hopefully clarify. Yes, it work exactly how I want when I manually type "/findthisvalue" in vim, It either highlights the value or says in the statusbar it wasn't found. The question is how to do that using the command line. – swdev Feb 24 '17 at 3:17
3

You can leverage the -c argument which runs a the given command after Vim has loaded. With this, you can search with ":silent!" which supresses all errors like so:

vim -c "silent! /foo" file_to_search.txt  

If found, it will jump to the result. Otherwise, Vim just loads up the file without any errors.

If you would still like an error message but skip the "Press ENTER" prompt, you can increase the 'cmdheight' option to 3.

Here's what I came up with to accomplish this: (Warning: I admit this is really hacky because it sets the cmdheight to 3, searches for the word, and then sets back the cmdheight to the default value of 1. Perhaps someone else can provide a better alternative):

vim -c "set cmdheight=3" +/word_to_search -c "set cmdheight=1" file_to_search.txt

In the above case, it will give you exactly what you asked for, Vim will print "E486: Pattern not found: findthisvalue" instead of the hit Enter prompt.

  • 1
    In my script, I was using stdin for the vim file. And that still doesn't work. For example. cat file_to_search.txt | vim -c "set cmdheight=3" +/word_to_search -c "set cmdheight=1" - does print anything in the statusbar. But I can change my script, so this solution works for me. Tx. – swdev Feb 24 '17 at 17:55

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.