[Bash] Variable exapansion and variables within variables

To make the following script more reusable, I wanted to refactor the "pattern" in a separate variable for the renameit2 function to use. However, it
currently doesn't work; "tr" throws an error:
tr: extra operand `\'-\''"
Can anyone explain how I can achieve what I'm trying to do?
Here is the complete script:
old="Hello THIS & test"
renameit() {
new=$(echo $old | \
tr ' ' '-' | tr -d '[{}(),\!]' | tr -d "\'" | tr '[A-Z]' '[a-z]' | \
sed -e 's/---/-/g' -e 's/&/-and-/g' -e 's/--/-/g' -e 's/_/-/g')
echo $new
PATTERN="
tr ' ' '-' | tr -d '[{}(),\!]' | tr -d "\'" | tr '[A-Z]' '[a-z]' | \
sed -e 's/---/-/g' -e 's/&/-and-/g' -e 's/--/-/g' -e 's/_/-/g'
renameit2() {
new=$(echo $old | $PATTERN)
echo $new
case $1 in
old)
renameit
new)
renameit2
esac

Hi,
I reworked your solution to use an array of sed expressions.
It becomes
patterns=( "s/[A-Z]*/\L\\\&/g" #replace uppercase with lowercase (\L\&)
"s/ /-/g" #replace spaces
"s/[{}\(\),\\!]//g" #delete some special chars
"s/\'//g" #delete the single quote
"s/[\\d038]/-and-/g" #replace the amperstad (ascii no 38 decimal)
"s/_/-/g" #replace underscores with dashes
"s/-\{2,\}/-/g" ) #translate all series of dashes to just one dash
renameit2() {
new="$old"
for p in "${patterns[@]}"
do
new=$(echo $new|sed -e "$p")
if [ -z "$new" ] ; then
echo "Failure at expression ${p}"
fi
done
echo $new
You could possibly do some xargs magic to cut the loop, but I couldnt be bothered.
This makes it easy to redifine, add, remove, or reorder individual rules. I reordered some of your rules and joined some other together, and I think I eliminated some possible bugs.
Last edited by gnud (2009-09-17 11:56:07)

Similar Messages

  • Creating variables in Process Flows and using thse variables in the filter

    Hi,
    I am new to OWB and in learing stage. Need to information.
    *1. as to how pass/create/use variables to OWB mapping ?*
    *2. Creating variables in Process Flows and using thse variables in the filter operator of the OWB mapping?*
    *3. Other mechanisms of how to create/use variables within OWB mapping itself ?*
    can you please provide the above details and guide me / help me in this regard.
    Thanks,
    skms.

    1. Add parameters to your mapping using the MAPPING INPUT PARAMETER from the pallette.
    2. Add parameters to the START operator in the process flow. Bind the process flow parameter to the Mapping parameter.
    3. May be appropriate to use CONSTANTS instead of parameters.
    Regards
    Si

  • How to Specify the environment variable JCE_POLICY_ZIP and restart

    Hello All,
    I am installing the ABAP SAP NetWeaver 7.01 SR1 ABAP Trial Version.
    sapinst.exe installed successfully.
    I am installing the sapinstgui.exe but I got the following message:
    Program is starting... Please wait!
      Path: C:\Users\George\AppData\Local\Temp\sapinst_exe.6220.1246290325
    jre\bin\java.exe
    For the requested processing mode java policy
    files within the used SAP JVM are needed.
    Specify the environment variable JCE_POLICY_ZIP and restart.
    See also SAP note 1238121.
    Exit status of child: 10
    JRE is installed in C:\Program Files\Java\j2re1.4.2_19
    How do I specify the environment variable JCE_POLICY_ZIP?
    Thanks
    George
    Edited by: George King on Jun 29, 2009 9:01 PM

    Hi everyone,
    I had the same problem and found the solution !
    I was trying to setup the GUI thanks to sapinstgui.exe from the trial download folder and I got the exact same message,
    The problem is not the policies but the installation file.
    The installation file for the GUI is located at :
    <extract_folder_SAP_trial_version>\GUI\SAP_GUI_FOR_WINDOWS(...)\SAP_GUI_for_windows_(...)_Components.exe
    Hope it helps !
    Nicolas

  • Having Trouble Copy and Pasteing Local Variable in LabVIEW 2010

    I am Having Trouble Copy and Pasteing Local Variable in LabVIEW 2010 in s subVI.
    I have a VI that has a Local Variable called "Node Addr". I can select it OK, and it appears to Copy OK, But when I go to paste it, nothing appears. It doesn't matter if I use Cntrl-C Cntrl-V or the Copy and Paste from the Edit menu, I get the same results. I tried many times and got the same results. I made sure that I had click a paste location. I can insert the Local Variable if I use the Data Communication panel.
    On one of the Paste, I got an error in the error list that said that a Local Variable was not connected to anything. When I clicked on the error, it took me to an insible item in the lower right corner of the block diagram that had nothing but a select box around it. I couldn't select the invisible item, but I could delete it.
    Why does the copy and paste of this local variable not work?
    Why does the paste cause the insertion of an invisible item?

    dbaechtel wrote:
     My VI is fairly complicated. In several places in the VI, I am either reading or writing to this variable which is an numeric Indicator on the Front Panel. Using local variables seems to be the best way to handle this situation rather that using wiring all over the VI. Since the VI is mainly a State Machine and there are only 2 Writes to the local variable, I am not afraid of race conditions in this case.  NO!! While you may think that using Locals is your solution to wiring, it is not!  The fact that you are writing and reading, most likely from several places, will most definitely contribute to a race condition.  Depending on your implemetation, you should ALWAYS use wires.  The wires are the variable.  If you are using a loop (While, For), then using shift registers are appropriate means for routing values so that they are used by other sections of the code, later.  One thing you must respect with LabVIEW is the dataflow.  That's where Locals often fail.
    I am not copying the Local Variable from one VI to another.
    I am not copying the Local Variable from one VI to another.
    The Data Communication panel is one of the panels that shows up in the Functions pop up list when editing the Block Diagram. It is the panel that includes the Local Variable function.
    I don't know if the invisible item that was inserted in my block diagram was hidden or not. All I know is that the Errors List said that it was a Local Variable and that it was not connected to anything. I couldn't select it to get more information. All I could do was delete it.
    You did not address my questions about why the Copy and Paste does not work properly for my Local Variable.  Maybe it's a sign from the Software Gods not to use them LOL!..
    So if I understand correctly, you are trying to copy & paste the Local Variable from within the same VI.  How large is your block diagram?  Did you try right-click on the variable and select "Find > Local Variables"?  If it's a block diagram larger than 1 single screen (which it shouldn't), then it is possible that the Local is hiding beyond the screen.  You should find it as I described earlier.
    See my comments in red above.

  • CRMOD Presentation variable scope and usage in drilldown report

    Hello dear all,
    I have dashboard and presentation variables on dashboard promt. When selecting these presentation variables all work fine within dashboard.
    But when I drilldown to another report that also uses these presentation varibales its not working.
    How to make possible to use presentation variables within dashboard ? Or maybe there is another way how to accomplish this.

    why do you want to show folder name for every column? folder name means name of the folder that reports saved in?? or presentation table name??
    you may use static rep variable to display folder name in report.
    Thanks
    Jay.

  • How to output variable names and units used in binary file

    My colleague will be giving me binary files (*.dat) generated from within LabView. There are over 60 variables (columns) in the binary output file. I need to know the variable names and units, which I believe he already has set up in LabView. Is there a way for him to output a file containing the variable name and unit, so that I'll know what the binary file contains? He can create an equivalent ASCII file with a header listing the variable name, but it doesn't list the units of each variable.
    As you can tell I am not a LabView user so I apologize if this question makes no sense.
    Solved!
    Go to Solution.

    Hi KE,
    an ASCII file (probably csv formatted) is just text - and contains all data that is (intentially) written to. There is no special function to include units or whatever!
    Your collegue has to save those information the same way he saves the names and the values...
    (When writing text files he could use WriteTextFile, FormatIntoFile, WriteToSpreadsheetFile, even WriteBinaryFile could be used...)
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • Javascript discussion: Variable scopes and functions

    Hi,
    I'm wondering how people proceed regarding variable scope, and calling
    functions and things. For instance, it's finally sunk in that almost
    always a variable should be declared with var to keep it local.
    But along similar lines, how should one deal with functions? That is,
    should every function be completely self contained -- i.e. must any
    variables outside the scope of the function be passed to the function,
    and the function may not alter any variables but those that are local to
    it? Or is that not necessary to be so strict?
    Functions also seem to be limited in that they can only return a single
    variable. But what if I want to create a function that alters a bunch of
    variables?
    So I guess that's two questions:
    (1) Should all functions be self-contained?
    (2) What if the function needs to return a whole bunch of variables?
    Thanks,
    Ariel

    Ariel:
    (Incidentally, I couldn't find any way of  marking answers correct when I visited the web forums a few days ago, so I gave up.)
    It's there...as long as you're logged in at least, and are the poster of the thread.
    What I want is to write code that I can easily come back to a few months later
    and make changes/add features -- so it's only me that sees the code, but
    after long intervals it can almost be as though someone else has written
    it! So I was wondering if I would be doing myself a favour by being more
    strict about make functions independent etc. Also, I was noticing that
    in the sample scripts that accompany InDesign (written by Olav Kvern?)
    the functions seem always to require all variables to be passed to it.
    Where it is not impractical to do so, you should make functions independent and reusable. But there are plenty of cases where it is impractical, or at least very annoying to do so.
    The sample scripts for InDesign are written to be in parallel between three different languages, and have a certain lowest-common-denominator effect. They also make use of some practices I would consider Not Very Good. I would not recommend them as an example for how to learn to write a large Javascript project.
    I'm not 100% sure what you mean by persistent session. Most of my
    scripts are run once and then quit. However, some do create a modeless
    dialog (ie where you can interface with the UI while running it), which
    is the only time I need to use #targetengine.
    Any script that specifies a #targetengine other than "main" is in a persistent session. It means that variables (and functions) will persist from script invokation to invokation. If you have two scripts that run in #targetengine session, for instance, because of their user interfaces, they can have conficting global variables. (Some people will suggest you should give each script its own #targetengine. I am not convinced this is a good idea, but my reasons against it are mostly speculation about performance and memory issues, which are things I will later tell you to not worry about.)
    But I think you've answered one of my questions when you say that the
    thing to avoid is the "v1" scope. Although I don't really see what the
    problem is in the context of InDesign scripting (unless someone else is
    going to using your script as function in one of theirs). Probably in
    Web design it's more of an issue, because a web page could be running
    several scripts at the same time?
    It's more of an issue in web browsers, certainly (which I have ~no experience writing complex Javascript for, by the way), but it matters in ID, too. See above. It also complicates code reuse across projects.
    Regarding functions altering variables: for example, I have a catalog
    script. myMasterPage is a variable that keeps track of which masterpage
    is being used. A function addPage() will add a page, but will need to
    update myMasterPage because many other functions in the script refer to
    that. However, addPage() also needs to update the total page count
    variable, the database-line-number-index-variable and several others,
    which are all used in most other functions. It seems laborious and
    unnecessary to pass them all to each function, then have the function
    alter them and return an array that would then need to be deciphered and
    applied back to the main variables. So in such a case I let the function
    alter these "global" (though not v1) variables. You're saying that's okay.
    Yes, that is OK. It's not a good idea to call that scope "global," though, since you'll promote confusion. You could call it...outer function scope, maybe? Not sure; that assumes addPage() is nested within some other function whose scope is containing myMasterPage.
    It is definitely true that you should not individually pass them to the function and return them as an array and reassign them to the outer function's variables.
    I think it is OK for addPage() to change them, yes.
    Another approach would be something like:
    (function() {
      var MPstate = {
        totalPages: 0,
        dbline: -1
      function addPage(state) {
        state.totalPages++;
        state.dbline=0;
        return state;
      MPstate = addPage(MPstate);
    I don't think this is a particularly good approach, though. It is clunky and also doesn't permit an easy way for addPage() to return success or failure.
    Of course it could instead do something like:
        return { success: true, state: state };
      var returnVal = addPage(MPstate);
      if (returnVal.success) { MPstate = returnVal.state; }
    but that's not very comforting either. Letting addPage() access it's parent functions variables works much much better, as you surmised.
    However, the down-side is that intuitively I feel this makes the script
    more "messy" -- less legible and professional. (On the other hand, I
    recall reading that passing a lot of variables to functions comes with a
    performance penalty.)
    I think that as long as you sufficiently clearly comment your code it is fine.
    Remember this sort of thing is part-and-parcel for a language that has classes and method functions inside those classes (e.g. Java, Python, ActionScript3, C++, etc.). It's totally reasonable for a class to define a bunch of variables that are scoped to that class and then implement a bunch of methods to modify those class variables. You should not sweat it.
    Passing lots of variables to functions does not incur any meaningful performance penalty at the level you should be worrying about. Premature optimization is almost always a bad idea. On the other hand, you should avoid doing so for a different reason -- it is hard to read and confusing to remember when the number of arguments to something is more than three or so. For instance, compare:
    addPage("iv", 3, "The rain in spain", 4, loremIpsumText);
    addPage({ name: "iv", insertAfter: 3, headingText: "The rain in spain",
      numberColumns: 4, bodyText: loremIpsumText});
    The latter is more verbose, but immensely more readable. And the order of parameters no longer matters.
    You should, in general, use Objects in this way when the number of parameters exceeds about three.
    I knew a function could return an array. I'll have to read up on it
    returing an object. (I mean, I guess I intuitively knew that too -- I'm
    sure I've had functions return textFrames or what-have-you),
    Remember that in Javascript, when we say Object we mean something like an associative array or dictionary in other languages. An arbitrary set of name/value pairs. This is confusing because it also means other kinds of objects, like DOM objects (textFrames, etc.), which are technically Javascript Objects too, because everything inherits from Object.prototype. But...that's not what I mean.
    So yes, read up on Objects. They are incredibly handy.

  • Problem with Threads and a static variable

    I have a problem with the code below. I am yet to make sure that I understand the problem. Correct me if I am wrong please.
    Code functionality:
    A timer calls SetState every second. It sets the state and sets boolean variable "changed" to true. Then notifies a main process thread to check if the state changed to send a message.
    The problem as far I understand is:
    Assume the timer Thread calls SetState twice before the main process Thread runs. As a result, "changed" is set to true twice. However, since the main process is blocked twice during the two calls to SetState, when it runs it would have the two SetState timer threads blocked on its synchronized body. It will pass the first one, send the message and set "changed" to false since it was true. Now, it will pass the second thread, but here is the problem, "changed" is already set to false. As a result, it won't send the message even though it is supposed to.
    Would you please let me know if my understanding is correct? If so, what would you propose to resolve the problem? Should I call wait some other or should I notify in a different way?
    Thanks,
    B.D.
    Code:
    private static volatile boolean bChanged = false;
    private static Thread objMainProcess;
       protected static void Init(){
            objMainProcess = new Thread() {
                public void run() {
                    while( objMainProcess == Thread.currentThread() ) {
                       GetState();
            objMainProcess.setDaemon( true );
            objMainProcess.start();
        public static void initStatusTimer(){
            if(objTimer == null)
                 objTimer = new javax.swing.Timer( 1000, new java.awt.event.ActionListener(){
                    public void actionPerformed( java.awt.event.ActionEvent evt){
                              SetState();
        private static void SetState(){
            if( objMainProcess == null ) return;
            synchronized( objMainProcess ) {
                bChanged = true;
                try{
                    objMainProcess.notify();
                }catch( IllegalMonitorStateException e ) {}
        private static boolean GetState() {
            if( objMainProcess == null ) return false;
            synchronized( objMainProcess ) {
                if( bChanged) {
                    SendMessage();
                    bChanged = false;
                    return true;
                try {
                    objMainProcess.wait();
                }catch( InterruptedException e ) {}
                return false;
        }

    Thanks DrClap for your reply. Everything you said is right. It is not easy to make them alternate since SetState() could be called from different places where the state could be anything else but a status message. Like a GREETING message for example. It is a handshaking message but not a status message.
    Again as you said, There is a reason I can't call sendMessage() inside setState().
    The only way I was able to do it is by having a counter of the number of notifies that have been called. Every time notify() is called a counter is incremented. Now instead of just checking if "changed" flag is true, I also check if notify counter is greater than zero. If both true, I send the message. If "changed" flag is false, I check again if the notify counter is greater than zero, I send the message. This way it works, but it is kind of a patch than a good design fix. I am yet to find a good solution.
    Thanks,
    B.D.

  • Difference between Temp table and Variable table and which one is better performance wise?

    Hello,
    Anyone could you explain What is difference between Temp Table (#, ##) and Variable table (DECLARE @V TABLE (EMP_ID INT)) ?
    Which one is recommended to use for better performance?
    also Is it possible to create CLUSTER and NONCLUSTER Index on Variable table?
    In my case: 1-2 days transactional data are more than 3-4 Millions. I tried using both # and table variable and found table variable is faster.
    Is that Table variable using Memory or Disk space?
    Thanks Shiven:) If Answer is Helpful, Please Vote

    Check following link to see differences b/w TempTable & TableVariable: http://sqlwithmanoj.com/2010/05/15/temporary-tables-vs-table-variables/
    TempTables & TableVariables both use memory & tempDB in similar manner, check this blog post: http://sqlwithmanoj.com/2010/07/20/table-variables-are-not-stored-in-memory-but-in-tempdb/
    Performance wise if you are dealing with millions of records then TempTable is ideal, as you can create explicit indexes on top of them. But if there are less records then TableVariables are good suited.
    On Tables Variable explicit index are not allowed, if you define a PK column, then a Clustered Index will be created automatically.
    But it also depends upon specific scenarios you are dealing with , can you share it?
    ~manoj | email: http://scr.im/m22g
    http://sqlwithmanoj.wordpress.com
    MCCA 2011 | My FB Page

  • Unit Testing and APEX Global Variables

    We've recently started to unit test our database level PL/SQL business logic.
    As such we have a need to be able to simulate or provide output from PL/SQL APEX components in order to facilitate testing of these components.
    Some of the most obvious portions that need simulation are:
    1. The existence of a session
    2. The current application ID
    3. The current page ID.
    We currently handle requirement #1 by using apex_040100.wwv_flow_session.create_new
    We handle 2 and 3 using the apex_application.g_flow_id and g_flow_step_id global variables.
    I'm just wondering, how safe is it for us to use wwv_flow_session.create_new to simulate the creation of a session at testing time for those things which need a session?
    I've also noticed that there are apex_application.get_application_id and apex_application.get_page_id functions whose output is not tied to the global variables (at least in our current version).
    Is it safe for us to expect that we can set these global variables for use in testing or is apex moving to get_application_id and get_page_id functions away from global variables?
    Will there be corresponding set_application_id and set_page_id functions in the future?
    Sorry for the question bomb. Thanks for any help.

    My first question would be why do you need to establish a session to test your PL/SQL?
    wwv_flow_session is a package internal to APEX, and you should probably leave it be.
    The get_application_id procedure you refer to is in apex_application_install, which is used for scripting installation of applications - not get/set of page ID like you're describing.
    If you're uncomfortable using apex_application.g_flow_id, you can use v('APP_ID') or preferably pass the app_id/page_id as parameters to your procedures.
    Your question seems to have a few unknowns, so that's the best I can describe.
    Scott

  • Apex listener installed no test and set bind variables buttons

    I have installed Apex listener and while creating restful service module i dont see test and set bind variables buttons in the source region.
    I went through the many posts. Installed apex listener successfully.
    getting http://localhost:8080/ords/ started message when i start the listener.
    and using Apex URL as http://localhost:7780/pls/htmldb.
    What are the possibilities for this issues?
    Please help me on this.
    Thanks
    Chandran

    Apex listener version is 2.0.9
    Apex version is 4.2

  • Do we need to update snpsagent.conf File and Windows Environmental variable in ERPI 11.1.2.2

    In ERPI 11.1.1.3 Admin guide its mentioned we need to update the below , do we need to do the same in 11.1.2.2 version also
    Updating the snpsagent.conf File
    ä To update the snpsagent.conf file:
    1 Navigate to the folder where Oracle Data Integrator is installed.
    For example, C:\OraHome_1\oracledi\tools\wrapper\conf.
    2 Using a text editor, open the snpsagent.conf file.
    3 Search for: wrapper.java.library.path.1.
    4 On a new line, add the following text:
    wrapper.java.library.path.2=../drivers
    5 Close and save the file.
    Updating the Windows Environment Variable
    After you update the snpsagent.conf file, add the ODI drivers path information to the
    Windows environment variable.
    ä To update the Windows environment variable:
    1 On the desktop, right-click My Computer, select Properties. Select the Advanced tab, and then click
    Environment Variables.
    2 In the System variables section, select the Path variable, and then click Edit.
    3 At the end of the Variable value line, add a semi-colon (;), and then add the Oracle Data Integrator
    driver path.
    For example, C:\OraHome_1\oracledi\drivers.
    4 Click OK three times.
    5 Restart the Oracle Data Integrator Agent Service.
    Thanks

    You should not have to do this in ODI 11.1.1.6 for ERPi 11.1.2.2.

  • How to find out the customer exit and sap exit variables created provider?

    Hi all,
    How to identify what are all the customer exit and sap exit variables are been created for an info provider. is there any tables which allow us to find out.
    thanxs
    haritha

    Hello haritha,
           SAP Exit and Customer Exit variables are created for  Characteristics and not for individual InfoProviders.
    So whenever the characteristic is used in the InfoProvider, by selection the appropriate variable the exit can be called.
    So the same Exit can be in one or more InfoProviders.
    Hope it helps.
    Thanks,
    Chandran

  • Install j2se plugin version 1.6.0_07 on your client and NPX_PLUGIN_PATH environment variable set before starting Netscape.

    Hi experts m new to apps please help.. I have installed successfully Oracle Apps R12 on OEL - 5 All the services runining fine. but when i am opening forms its giving error "install missing plugins" i installed jre-6u7-linux-i586-rpm.bin and Mozilla Firefox 3.0.18 [root@ust ~]# cd firefox/plugins/ [root@ust plugins]# ln -s /usr/java/jre1.6.0_07/plugin/i386/ns7/libjavaplugin_oji.so ./libjavaplugin_oji.so [root@ust plugins]# ls libjavaplugin_oji.so  libnullplugin.so [root@ust plugins]# ll total 20 lrwxrwxrwx 1 root root    58 Sep 11 16:22 libjavaplugin_oji.so -> /usr/java/jre1.6.0_07/plugin/i386/ns7/libjavaplugin_oji.so   -rwxr-xr-x 1 root root 19160 Sep 15  2007 libnullplugin.so [root@ust plugins]# but when m trying to open forms at that time giving error "install j2se plugin version 1.6.0_07 on your client and NPX_PLUGIN_PATH environment variable set before starting Netscape."

    Linux is not a certified client tier for accessing EBS
    Unable to access r12 forms in linux client
    https://forums.oracle.com/search.jspa?view=content&resultTypes=&dateRange=all&q=linux+client&rankBy=relevance&contentTyp…
    HTH
    Srini

  • Variable filename and folder in receiver cc

    Dear experts,
    On PI, I need to create a (text-) file with a variable name and folder. The scenario is as follows:
    idoc-> PI -> txt file
    In my incoming Idoc I get the following data:
    - directory where the txt file should be saved;
    - name that the txt file should get.
    How can I realise this in PI? Using variable substitution? As I never done this before, I have a hard time getting this to work...
    Please help.
    Thanks in advance
    William

    Hi,
    Use Dynamic Configuration:
    Input will be 2 variables var1, var2.
    String Name1 = var1;
    DynamicConfiguration conf = (DynamicConfiguration) container.getTransformationParameters().get(StreamTransformationConstants.DYNAMIC_CONFIGURATION);
    DynamicConfigurationKey key1 = DynamicConfigurationKey.create("http://sap.com/xi/XI/System/File", "FileName");
    conf.put(key1, Name1);
    String Name2 = var2;
    DynamicConfigurationKey key2 = DynamicConfigurationKey.create("http://sap.com/xi/XI/System/File", "Directory");
    conf.put(key2, Name2);
    return "";
    Maping:
    Var1---
    UDF----TargetMessageNode.
    Var2---
    Under ID: Enable ASMA in file receiver adapter and chk FileName and Directory.
    and put * under File name and / underTarget Directory(File receiver).
    NOTE: U can alter this UDF according to ur req.
    Thanks
    Amit

Maybe you are looking for