Kate and replace with regular expressions

Just got good experience with KDE’s Kate editor and must share it.

You have piece of code, which looks like this

if(get_var('submit')){
    // still empty..
}else{
    $var1=null;
    $var2=null;
    ...
    $var100=null;
}

and now you need to put those initializations of var’s to the first block also, getting variables from GET or POST supervariables. What to do? Doing hunderd times of “delete null, paste get_var(”), copy-paste ‘name of variable'” and the day is going to be sooooo long …

Now, in Kate you can do it by one click. Copy all lines “$var..=null;” to first block, select those lines and “ctrl+r” (replace) and put values:

Find: \$(.*)=null;
Replace: \$\1=get_var('\1');
Mode: Regular expression
[V] Selection Only (just incase)

and press “Replace All”. And it’s done:

if(get_var('submit')){
    $var1=get_var('var1');
    $var2=get_var('var2');
    ...
    $var100=get_var('var100');
}else{
    $var1=null;
    $var2=null;
    ...
    $var100=null;
}

and explained:
In Find expression you see (.*) – content of parentheses are treated as parameter “one” and referenced later as \1. That what you see in Replace expression \$\1 – will get replaced as “$var1” and get_var(‘\1’) gets get_var(‘var1’)

This entry was posted in Uncategorized. Bookmark the permalink.

2 Responses to Kate and replace with regular expressions

  1. Vidmantas says:

    Maybe you know how to replace 10th match?
    for example search is: (.*)\t(.*)\t(.*)\t(.*)\t(.*)\t(.*)\t(.*)\t(.*)\t(.*)\t(.*)\t(.*)\t(.*)
    you can replace correctly \1 \2 .. \9
    but on 10th match you get 1st match + zero

  2. Urmas says:

    One possible way is to switch other languages, like awk or perl – much powerful tools to use. Remember, if you use shell scripts, you can easily write one line in other languages.

    Second possibility, is to do little trick – you match 8 fields as you do now, and then ALL the rest of line as 9th field, and on that field do separate matching.

    Eg smth like that (warning: written without testing, just example):

    first_part=`echo "alpha beta gamma delta" | sed -e 's/(.*) (.*)/\1/'`;
    second_part=`echo "alpha beta gamma delta" | sed -e 's/(.*) (.*)/\2/' | sed -e ' [here you will do actions with "beta gamma delta"] '`

Leave a Reply

Your email address will not be published. Required fields are marked *

Exaptcha (all lowercase letters) reload *