Variable in regex replace pattern

Hi,
I need to use a variable in a regex replace pattern - how can I do it? Specifically, I need to pass arguments to a shell script that then uses that argument in a replace pattern:
#!/bin/bash
#$1 now holds the argument
sed 's/searchpattern/replace_pattern_with_variable$1/g' file1 > file2
when I run this, the replace pattern uses $1 as a literal string "$1" and not the variable value. How can I change this?
Thanks!
Ingo

Hi Ingo,
   As Vid points out, the issue is that single quotes protect strings from shell interpretation. You need to have the dollar sign, '$', visible to the shell or it won't read what follows as a variable name. Using double quotes works because the shell "reads through" those.
   However, complex regular expressions can contain lots of characters that the shell interprets. These can be quoted individually by backslashes but the use of backslashes in regular expressions is complex enough without the addition of shell interpretation. I find it easiest to keep the single quotes and only expose the part of the string that the shell needs to interpret.
   The shell doesn't have a special string concatenation character. All you have to do is to put the strings beside each other with nothing in between and the shell will concatenate them. Therefore it's possible to write your example as:
sed 's/searchpattern/replace_pattern_with_variable'${1}'/g' file1 > file2
That is, one closes the single quote right before the variable and then resumes it immediately afterward. The shell will put these quoted strings together with the contents of the variable just as it would with double quotes but you still enjoy the protection of single quotes around the rest of the string!
Gary
~~~~
   P.S. Perl's master plan (or what passes for one) is to take
   over the world like English did. Er, as English did...
      -- Larry Wall in <[email protected]>

Similar Messages

  • Applescript Regex Replace Usage

    I am using Applescript to do regex replace for a pattern of type APP[0-9][0-9][a-z][a-z] and display it as a hyperlink.
    Eg: APP23cc to APP23cc
           APP36ij to APP36ij
    I am getting the body of the email as a string.
    How could I do this?

    I'm not exactly clear on what you're trying to do (display the hyperlink where and how? what link are you trying to link?), but I can say that applescript does not do regexp natively.  you have two choices:
    download the Satimage osax so that you can do regexp
    use a simpler search pardigm
    a simpler search would require a repeat loop, like so:
    repeat with w in words of body
              considering case
                        if w begins with "APP" then
      -- do whatever you're trying to do here
                        end if
              end considering
    end repeat
    you can make that IF as detailed as you need it to be to specify the things you want to work with.

  • Understanding Regex replace method call involving delegate

    Hello,
    I am trying to understand the $regex.replace static method call below (I came across this code snippet in the cookbook).
    $replacer = {
    param($match)
    $chars = $match.Groups[0].Value.ToCharArray()
    [Array]::Reverse($chars)
    $chars -join ''
    $regex = [Regex] "\w+"
    $regex.Replace("Hello World wide", $replacer)
    What I do not understand is the below overloaded definitions for replace method do not seem to match the above replace call. So how exactly is this working? The above call has 2 parameters passed where as none of the below overloads have less than
    3 parameters.
    PS C:\WINDOWS> [regex]::replace
    OverloadDefinitions
    static string Replace(string input, string pattern, string replacement)
    static string Replace(string input, string pattern, string replacement, System.Text.RegularExpressions.RegexOptions options)
    static string Replace(string input, string pattern, string replacement, System.Text.RegularExpressions.RegexOptions options, timespan matchTimeout)
    static string Replace(string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator)
    static string Replace(string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator, System.Text.RegularExpressions.RegexOptions options)
    static string Replace(string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator, System.Text.RegularExpressions.RegexOptions options, timespan
    matchTimeout)

    What you are looking at are the static methods ([regex]::) and their appropriate parameters which in this case have a minimum of 3 parameters to properly perform the Replace using the input, pattern and replacement
    value. If you were to use the constructor of [regex] to create a pattern like this:
    $Regex = [regex]'\w'
    You will see that the Replace method here allows for only 2 parameters because you have already satisfied the pattern when you created the Regex object.
    $Regex.Replace
    OverloadDefinitions
    string Replace(string input, string replacement)
    string Replace(string input, string replacement, int count)
    string Replace(string input, string replacement, int count, int startat)
    string Replace(string input, System.Text.RegularExpressions.MatchEvaluator evaluator)
    string Replace(string input, System.Text.RegularExpressions.MatchEvaluator evaluator, int count)
    string Replace(string input, System.Text.RegularExpressions.MatchEvaluator evaluator, int count, int startat)
    Boe Prox
    Blog |
    Twitter
    PoshWSUS |
    PoshPAIG | PoshChat |
    PoshEventUI
    PowerShell Deep Dives Book

  • Possible to do variable number of REPLACE in SQL?

    Hello. Using Oracle 10G, R2
    Wondering if it is possible to do a variable number of REPLACE() entirely in SQL in a view.
    input_table.text_column = This (b)is(/b) some (i)text(/i) with (u)formatting(/u) codes
    Note: Using ( and ) to represent < and >
    rows in format_codes_table:
    (b)
    (/b)
    (i)
    (/i)
    (u)
    (/u)
    (p)
    (/p)
    etc. (The number of format_codes is not fixed)
    Desired output: This is some text with formatting codes
    This could be done with a user-defined function and then use that function in a SQL:
    create or replace function remove_format_codes(input_p IN varchar2)
    return varchar2
       v_output   varchar2(2000);
    is
    begin
       v_output := input_p;
       for r1 in (select format_code from format_codes_table)
       loop
          v_output := replace(v_output, r1.format_code);
       end loop;
       return v_output;
    end;
    create or replace view unformatted_output_vw
    as
    select remove_format_codes(input_table.text_column) as unformatted_output
    from input_table
    /I tried this SQL:
    select replace(input_table.text_column, format_codes_table.format_code) as unformatted_output
    from input_table
        ,format_codes_table
    /But it only replaces one format code at a time, and it is not recursive so the output is like this:
    This is(/b) some (i)text(/i) with (u)formatting(/u) codes
    This (b)is some (i)text(/i) with (u)formatting(/u) codes
    This (b)is(/b) some text(/i) with (u)formatting(/u) codes
    This (b)is(/b) some (i)text with (u)formatting(/u) codes
    etc.
    I've google'd Oracle recursive sql, looked at CONNECT BY, LEAD, LAG, MODEL, and I've also looked at a
    Tom Kyte example for varying in lists (http://tkyte.blogspot.com/2006/06/varying-in-lists.html),
    but I can't seem to find a way to replicate the loop in my user-defined function in SQL.
    Anyone think this is possible in SQL? If yes, any hints?
    Thanks

    Hi,
    Regular expressions (introduced in Oracle 10) are great for this:
    SELECT     REGEXP_REPLACE ( text_column
                     , '&lt;'          || -- left angle-bracket
                       '/?'          || -- optional slash
                    '[bipu]'     || -- any one of these characters
                    '>'             -- right angle-bracket
                     )      AS no_tag_text
    FROM    input_table
    ;You had some good ideas: recursive subqueries (new in Oracle 11.2), CONNECT BY and MODEL could also do this job, but not nearly as easily.
    In case you're interested, the following thread uses MODEL to do nested REPLACEs:
    SQL Query
    Edited by: Frank Kulash on May 13, 2010 4:08 PM
    Edited by: Frank Kulash on May 17, 2010 1:02 PM
    Fixed link

  • Efficient regex replace function? Help!

    Here's what I'm trying to do:
    Scan through a string, and replace any occurences of http://...... (until the next space) with an HTML link. Does anyone know what would be the most efficient regex replace function to do this?
    Thank you very much in advance.

    class StringReplaceDemo{
         public static void main (String args[]){
              String mystr = "This is hyperlink to Google http:// . From there you can search for any thing in the world";
              String google = "http://www.google.com";
              String hyperlink = "http://";
              int hyperlinklength = hyperlink.length();
              int index = mystr.indexOf("http://");
              mystr = mystr.substring(0,index)+google+mystr.substring((index+hyperlink.length()),mystr.length());
              System.out.println(mystr);
    }

  • How to feed a query using a variable defined as Replacement Path-Query

    Scenario description : BI NetW 2004S - InfoCube with the following characteristics Customer, OrderDate, OrderYear and the following KeyFigure Number of Pieces.
    Objective: I need a query "QB" that shows how many pieces a set of customers has ordered in the year 2008. The set of customers is defined as all customers that in the previous years (the user can select one or more years) have ordered more than 500 pieces within the same year.
    Implementation: In general terms the idea is to build a query "QB" with the characteristic "Customer"  that is restricted (filtered) using a variable that is fed by another query "QA" (Replacement Path-Query).
    In order to have the selection of customers that for each of previous years (2007, 2006, 2005,...) have ordered more than 500 pieces, in the query "QA":
    - I put OrderYear as filter and defined a variable in order to ask the user which year/s he wants to analyse to define the selection
    - I put Customer and OrderYear in row
    - I put the KeyFigure Number of Pieces in column
    - I've defined the following condition: Number of Pieces > 500 with the option Caracteristic Assignment = All Characteristics in the Drilldown Indipendently
    Now if I run the query "QA" it works correctly showing me all customers that in the selected years have ordered more than 500 pieces within of the same year.
    If I run the query "QB" it shows a correct result only if I enter only one year (for example 2006) in the OrderYear field (coming from the query "QA"); if I enter more than one year (for example 2006 and 2007) the selection of customers showed is not the same defined by the first query "QB": I was expecting to see all customers defined from the first query less all customers that have no ordered any piece in 2008.
    Questions
    1) Why is query "QA" working on a different selection of customers when the user selects more than one year?
    2) Cosidering the scenario and the objective described above do you have any other idea?
    Thanks
    Ciao
    Roberto

    Hi Christophe,
         it's ok for me if I consider the customer only once in the final selection of customers that feeds the final query, this is my objective.
    However as test I've created 2 "input" queries, one related to 2006 and one related to 2007, and then in my destination query I've tried to restrict the customer using 2 variables of type replacement path-query (one attached to the 2006 query and one attached to the 2007 query). Unfortunately when I try to check and save the destination query, Query Designer tells me it is not possible to restrict the characteristic in this way.
    Could you please describe me steps you run in to order to restrict a characteristic using more than one variable of type replacement path-query?
    Thank you in advance for your answer.
    Ciao,
    Roberto

  • Formula variable of type replacement path not working

    Hi Folks,
    I have created formula variable of type replacement path and replaces with characteristic key.I wanted to use charecteristic infoobjects in coluns so that i have created formula variable for that.But when excecuting the query in web it is not displaying values for that formula.
    Can anyone plz solve this,if u come accross this situation before.
    Thanks and Regards,
    Ravikiran
    Edited by: MRK@SAPBI on Jun 11, 2011 1:13 PM

    Thanks vineet, for your quick reply.
    yes,i have used the characteristic in a row and it is a number.
    Still it is not displyaing values.But i need to calculate the couter for the same formula created on that charateristic and need to put condition in the query.
    thanks,
    Ravikiran

  • A formula with a formula variable with a replacement path delivers X

    A formula with a formula variable with a replacement path delivers X as a result if the characteristic of the replacement is not in the drilldown
    I have Created on ( date ) on which I have a Formula variable . I have used that Formula Variable in my calculated Key figure .
    Now the Problem is If I use Created on in ROW , The calculated key figure works . But if I don't use in Row , The calculated Key figure shows X . Situation is Users don't want to see Created on in ROW .
    If I use in row and hide also , then number of Records  will be same .
    Pls guide me what shoud I do .
    Is this problem related to support pack .

    hi
    i would like to know how to create the replacement path and authorisation variables.
    what are the steps we need to follow in rsa1.
    Edited by: vasu reddy on Apr 9, 2008 11:28 AM

  • Query Designer BI 7.0 (create variable to capture a pattern like in V3.5)

    Thank you in advance for your comments and help.
    In V3.5 of query designer  you could create a variable to capture a pattern in the characteristic.
    How do you do that in V7.0?

    Hi!
    Does anybody know how to create a resticted key figure on a given pattern (i.e. 0material = 'RC*') just like in 3.x?
    Thanks in advance
    LJ.

  • Broadcasting - Variable with Query Replacement Rule - java.lang.OutOfMemory

    Hi there,
    We recently upgraded to BW7/SPS 23 and since then one of my queries which is broadcasted is getting an error:
    - Error: java.lang.OutOfMemoryError 
    The unique thing about this query is that it uses a variable which a replacement path from a query.
    Does anyone know how to fix this?
    Thanks, Audrey

    Please check the following note regarding the sizing of your Netweaver installation
    https://service.sap.com/sap/support/notes/927530
    Regards,
    Stratos

  • Using a local variable in regex portion of replaceAll(regex, replacement)

    While this works..
    output = output.replaceAll("(HED>|AUT>)(.*)(</\\1)", "$1<![CDATA[$2]]>$3");
    I'd like the list of alternation values to be contained in a variable, for example:
    String nodeLIst = "HED>|AUT>";
    output = output.replaceAll("(nodeList)(.*)(</\\1)", "$1<![CDATA[$2]]>$3");
    The extension of this would be so I can store this stuff in a db as a list and avoid compilation on change, but please don't let this muddy the waters... :)
    Any pointers are much appreciated. Links to specific reading material, etc. I've scoured Friedl's Mastering Regular Expressions to no avail. This approach is supported by some other regex engines I've used (perl, php, ORO?) but I'm new to Java.
    TIA,
    Mark

    I've scoured Friedl's Mastering Regular Expressions to no avail.Did you look on page 209? In the book, that code sample is labelled "Building Up a Regex Through Variables in Java". That should have been a clue. ^_^
    But seriously, you're probably thinking of the interpolated strings you find in scripting languages like Perl, PHP, Ruby, etc.. But that's a feature of the language itself, not the regex engine, and Java doesn't work that way. (The $1, $2, etc., in the replacement string are processed by the Matcher class, in a very limited imitation of Perl's variable interpolation).
    However, you can fake it pretty well with String's format() method:   String regex = String.format("(%s)(.*)(</\\1)", theAlternation);
      output = output.replaceAll(regex, "$1<![CDATA[$2]]>$3"); That way, you can easily escape the dynamic part, in case it might contain regex metacharacters:   String regex = String.format("(%s)(.*)(</\\1)", Pattern.quote(theAlternation));

  • Java.util.regex and replacing patterns with function calls

    Hi everyone,
    I'm in terrible need for help.
    Any advice is much appreciated.
    I have the following sentence in a file. The sequence of numbers is actually a
    date in seconds since 1970. I need to identify the 9 or 10 sequence of numbers
    send that to a method that will transate the numbers into a date in a string format.
    Then replace it in the file.
    Here is an example:
    "My name is Peter. Please 1020421277 help me figure this out 108062327. "
    using the following block I can convert it to this
    "My name is Peter. Please | help me figure this out |. "
    [block]
    Pattern p = Pattern.compile("[0-9]{9,10}+");
    Matcher m = p.matcher("");
    String aLine = null;
    while((aLine = in.readLine()) != null) {
    m.reset(aLine);
    String result = m.replaceAll("|");
    out.write(result);
    out.newLine();
    [end block]
    So I need to change the above block so that my sentence looks like this.
    "My name is Peter. Please 05/03/2002 10:21:17 help me figure this out 06/04/1973 17:18:47. "
    The method that converts the numbers into a date is not of a concern because I already have
    the code to do that.
    If anyone has suggestion, please let me know.
    Thanks in advance.
    Peter
    [email protected]

    Never mind, I was able to figure it out....
    Common2 cm = new Common2();
    Pattern p = Pattern.compile("[0-9]{9,10}+");
    Matcher m = p.matcher("");
    m = p.matcher(s1);
    while ((found = m.find())) {
    String replaceStr = m.group();
    System.out.print("\tReplaceString is: " + replaceStr);
    replaceStr = cm.get_date(replaceStr);
    System.out.println("\t\tConverted to: " + replaceStr);
    m.appendReplacement(buf,replaceStr);
    m.appendTail(buf);
    ----------------- The get_date method in Common2 looked like this ------------------------------
    public String get_date(String myString)
    String s;
    long lsecs = Long.parseLong(myString);
    lsecs = lsecs * 1000; // its now milliseconds.
    // Determine default calendar and then the offset to GMT.
    Calendar localCalendar = Calendar.getInstance();
    int offset = localCalendar.get(Calendar.DST_OFFSET) + localCalendar.get
    (Calendar.ZONE_OFFSET);
    // Take the number of milliseconds subtract the gmtoffset
    Date GMTdate = new Date(lsecs - offset);
    // Format date
    Format myformat;
    myformat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a z ");
    s = myformat.format(GMTdate);
    return s;
    Peter

  • RegEx replacement

    I'm trying to make a small parsing engine that does the following:
    1. reads an HTML document
    2. searches for special tags of the form [key]
    3. looks up the key in a hashmap or something
    4. replaces [key] with value from the hashmap
    I'm storing the HTML document line by line as strings in an ArrayList (any better way to do this?). I iterate through each line, replacing each tag with its corresponding value. The thing is, however, that I'd like to use RegEx as much as possible.
    The java.lang.String.matches(String regex) method tells me, through a boolean return value, whether the current line actually contains any tag at all , while the java.lang.String.replaceFirst(String regex, String replacement) method solves the replacement part. What the String class methods don't provide me with is a method for returning the actual substring that was found during the java.lang.String.matches(String regex) call. Is there any such method out there? Right now I'm doing this manually, using the String class' indexOf(...) and lastIndexOf(..) methods.
    In short, what I'm looking for is a method something like String find(String text, String regex) that would return "salary" when called as find("<h1>[salary]</h1>", ".*\\[.*\\].*")
    Thanks for your help!

    You must use Patterns and Matchers (java.util.regex.*).
    In short, what I'm looking for is a method something like String find(String text, String >regex) that would return "salary" when called as find("<h1>[salary]</h1>", ".*\\[.*\\].*")Let's
    String html
    be your input.
    Pattern p = Pattern.compile("(?im)<h1>(.*?)</h1>");
    Matcher m = p.matcher(html);
    if( m.find() ){
    // the whole matching substring is in m.group();
    // the string within the h1's is in m.group(1)
    }

  • Re: HowTo? Replacement pattern for StringSubstitution?

    With Perl compatible regular expressions, I can have a regex do string replacement with \1 to represent the pattern to be preserved in the replacement.
    IMG_1234.cr2 --> YYMMDD_061234_Description.cr2
    using a pattern such as:
    IMG_([0-9]{4}).cr2 --> YYMMDD_06\1_Description.cr2
    This doesn't work in Bridge, and I don't see what "token" to use as a "placeholder" for the part of the string to be preserved.
    In the above example, the ([0-9]{4}) is recognized, but I don't see how to reuse that placeholder.

    You can use $1 to represent the matching part.

  • HowTo? Replacement pattern for StringSubstitution?

    With Perl compatible regular expressions, I can have a regex do string replacement with \1 to represent the pattern to be preserved in the replacement.
    IMG_1234.cr2 --> YYMMDD_061234_Description.cr2
    using a pattern such as:
    IMG_([0-9]{4}).cr2 --> YYMMDD_06\1_Description.cr2
    This doesn't work in Bridge, and I don't see what "token" to use a a "placeholder" for the part of the string to be preserved.
    In the above example, the ([0-9]{4}) is recognized, but I don't see how to reuse that placeholder.

    Try the Bridge Scripts forum.

Maybe you are looking for