tags:

views:

352

answers:

3

I have some mismatching if and fi statements in a script. I would like to strip out everything but the if's else's and fi's. Just so I can see the structure. Why am working so HARD with such a powerful editor? I need a BIGFATOR operator for regexp or some epiphany that has eluded me... I don't care for pontification on regular expressions just something practical working in VIM7.2.

:g/[ ^\t]if [/print

will print out the ifs

:g/[ ^\t]fi/print

will printout the fi

What I want to do is or the conditions

:g/[ ^\t]fi BIGFATOROPERATOR [ ^\t]fi/print

I have had success doing the following... but I feel I am working TOO HARD!

:call TripMatch('[ ^\t]*if [', 'else', 'fi[ \t$]')

function! TripMatch(str1, str2, str3)

let var1 = a:str1

let var2 = a:str2

let var3 = a:str3

let max = line("$")

let n = 1

for n in range (1, max)

let currentline = getline(n)

if currentline =~? var1

   echo n "1:" currentline

else

   if currentline =~? var2

      echo n "2:" currentline

   else

      if currentline =~? var3

         echo n "3:" currentline

      else

         let foo = "do nothing"

      endif

   endif

endif

endfor

endfunction

+6  A: 
:g/[ ^\t]if\|[ ^\t]fi/print

BIGFATOROPERATOR is \|. It's called the alternation operator. In PCRE, it's plain |. It's escaped in Vim/ex because | is used elsewhere for general commands (or something -- FIXME).

strager
Are you infact escaping the | character in that?
ojblass
In my defense there is an awful lot of noise searching for these things... and a I did learn a lot in the process.
ojblass
Um... I hate you but I love you... thanks for making me less of an idiot.
ojblass
+4  A: 

If you want to remove all other lines aside from those with if, else or fi you can use this

%v/\(if\|else\|fi\)/d

'v' is the opposite of 'g' and will remove any lines that don't match the regexp.

To add to what strager said, the pipe character '|' is escaped in Vim, I imagine because Vim assumes you'll be looking for literal characters more often than you will have need of extensive RegExps.

You can make Vim use less escaped RegExps by setting the 'magic' level to 'very' when in ex mode:

Use of "\v" means that in the pattern after it all ASCII characters except '0'-'9', 'a'-'z', 'A'-'Z' and '_' have a special meaning. "very magic"

See :he /magic for more information

It is not recommended that you set the default magic level to 'very' in your vimrc though (as the help file notes).

Flemish Bee Cycle
alternation operator yet again... where did I miss this in my education?
ojblass
The unescaped pipe character is used to string Ex commands together. For example :bufdo retab | updatewill execute :retab and :update on every buffer.
George V. Reilly
+2  A: 
:h /\|

If you missed \|, you probably have missed many other pattern "tokens".

Luc Hermitte