Saturday, April 30, 2011

Re: determine if a certain line occurs in a file

Reply to message «determine if a certain line occurs in a file»,
sent 15:47:43 30 April 2011, Saturday
by cyboman:

You can either force vim to ignore an error message by using `silent!', or use
`search()':

let oldy='2010'
let newy=strftime('%Y')
let line=search('Copyright '.oldy.', Company E', 'n')
if line
call setline(line, substitute(getline(line), oldy, oldy.'-'.newy, ''))
endif
My version with setline/getline and 'n' argument to `search()' does not move the
cursor.

Original message:
> i'm trying to write a small vim function which will modify a copyright
> year each time i'm opening a file. here is what i came up with
>
> function UpdateCopyrightYear()
> let l:cmd = 's/\(\d\+\)/\1-'.strftime("%Y").'/'
> g/Copyright 2010, Company E/exec l:cmd
> endfunction
>
> the problem that i'm facing right now is if the pattern is not in the
> file, i get an error message, E486: Pattern not found Copyright 2010,
> Company E. is there a way to tell vim not to execute the command if
> pattern is not found, say something like:
>
> function UpdateCopyrightYear()
> let l:cmd = 's/\(\d\+\)/\1-'.strftime("%Y").'/'
> if g/Copyright 2010, Company E/
> g/Copyright 2010, Company E/exec l:cmd
> endif
> endfunction
>
> thanks, any help is appreciated.

No comments: