Sorting lines by length in automator?

I have a document with around 4,000 lines of text. Is there a way for me to automatically sort them by character length through the use of Automator and a bit of scripting?
Bonus points if there's a way to output the character length at the beginning of each line once the sorting is complete.
Little heads up, my knowledge of AppleScript is pretty non-existant so an idiot's guide would be much appreciated.

There's nothing wrong with the script, it's the format of your text file that's causing the problem.
Unfortuntely there isn't really such as thing as a 'plain' text file anymore. Text files come in a variety of formats (ASCII, Unicode, ISO, etc.) and use varying line endings (CR, LF, or CR/LF), and the particular combination used in your file is breaking the script.
The simplest solution is to save the file as standard UTF-8 Unicode, then the script works fine. If you don't have an application that can convert it you can incorporate the command line utility textutil into your shell command:
textutil -convert txt -o - $1 | awk '{print (length($0) " " $0 "</sentence>")}' | sort -n
This time it will invoke textutil to convert the file first (rather than just cat, then run the awk/sort commands.

Similar Messages

  • How can I sort lines of data (alphabetically) in the new pages 5.0?

    How can I sort lines of data (alphabetically) in the new pages 5.0?
    It was very simple to do in the previou version of pages.

    I'm not sure why people are torturing themselves with Pages 5 given the nearly universal outcry on this forum and the incredibly negative reviews elswhere, such as the App Store.
    Pages 4.3 should still be in an iWorks folder within your Applications folder.  Just use that.
    Please remember to tell Apple what we need from them at:
    http://www.apple.com/feedback/pages.html

  • Sort by focal length

    1. Metadata Browser: sort by focal length (using a cushioned range)
    2. Ability to filter based on focal length: i.e. with 3 criteria lens, focal length, aperture it would be super simple to paint in presets for removing natural vignetting.

    Ian,
    The post in which I repeated your comment was not directed at you, the quote was used to re-iterate that it is accepted that the feature is currently not available, and that the search feature is very limited.
    If you feel my post was directed at you, my apologies. If you reread the post, the only two times the word "you" was used was in the following way:
    >"If you build it, they will come..." well, "If the information is there, you should be able to search, filter, or create smart collections by it."
    The comment should have started with "With all due respect to the LR team..." because I hate harping on a subject, with anyone. However, this thread was initiated on July 10, 2007 and covers an issue that deserves to have been addressed by now.
    After all, LR is a database program designed with photographers in mind. All databases work in the same way:
    1. They provide a way to input/gather information
    2. They store the information in fields, and
    3. They allow you to obtain that information through reports, or other means, so you can use it constructively. LR gathers the focal length information separately from the lens information. Therefore, it should be easy to program it to allow you to filter/search/create collections on the information.
    Regards, JML

  • How to Sort by the length of the returned value from a query.

    Hi,
    I was wondering if it is possible to sort by the length of the returned value from a query?
    For example if I want to get a list of people with the name 'Samuel', I would like to short by how short the length of the whole name is.
    Sort by length of the name in SQL
    Samuel Syda
    Samuel Indranaka
    Samuel Johnsons
    Samuel Longhenderson
    Thank you.

    Hi,
    Sorting is done by an ORDER BY clause at the end of the main query.
    In most cases, you can ORDER BY any expression, even f it is not in the SELECT clause.  In this case, it sounds like you just need:
    ORDER BY  LENGTH (name_column)
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data.
    Post your query, using an ORDER BY clause like the one above, and point out where that query is producing the wrong results, and explain, using specific examples, how you get the right results from the given data in those places.
    Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
    See the forum FAQ: https://forums.oracle.com/message/9362002

  • OrderedList sorted by String length

    i am trying to create an orderedlist of strings in ascending order by length. I am a little shacky on comparables this is what i have so far. I think i have to implement the Comparable interface and use length as the comparison in the Word class but im not entirely sure how to do this. So for example lion, pig, crocodile should look like ....
    pig
    lion
    crocodile
    in the ordered list... any help is appreciated.
    WORD.JAVA
    public class Word
         private String word, description;
         private int startPos, direction, used;
         public static final int NOTUSED = 0;
         public static final int USED = 1;
         public static final int DOWN= 0;
         public static final int ACROSS= 1;
         public Word(String w, String d)
              word = w;
              description = d;
              //startPos = num;
              //direction = dir;
              //used = use;
         public void setDirection(int dir)
              direction = dir;
         public int getDirection()
              return direction;
         public void setUsed(int use)
              used = use;
         public int getUsed()
              return used;
         public void setPos(int num)
              startPos = num;
         public int getPos()
              return startPos;
         public String getDescription()
              return description;
         public String getWord()
              return word;
         public String toString()
              String str = "";
              str = word+": "+description;
              return str;
    ORDEREDLIST.JAVA
    import java.util.*;
    public class OrderedLinkedList
         private class LinearNode
              private LinearNode next = null;
              private Comparable element = null;
              public LinearNode(Comparable c)
                   element = c;
              public LinearNode getNext()
                   return next;
              public void setNext(LinearNode n)
                   next = n;
              public Comparable getElement()
                   return element;
              public void setElement(Comparable c)
                   element = c;
              public String toStringRecursive()
                   String result = element.toString();
                   if(next == null)
                        return null;
                   else
                        return result + " " + next.toStringRecursive();
              public void add(LinearNode node)
                   if(node.element.compareTo(next.element) <= 0)
                        node.next = next;
                        next = node;
                   else
                        next.add(node);
         private LinearNode first = null;
         private LinearNode last = null;
         private int count = 0;
         public void add(Comparable c)
              LinearNode node = new LinearNode(c);
              if(isEmpty())
                   first = node;
                   last = node;
              else if(count == 1)//(first == last)
                   if(c.compareTo(first.getElement()) > 0) //one in list add to end
                        last = node;
                        first.setNext(last);
                   }else                                   //one in list add to start
                        first = node;
                   first.setNext(last);
              else if(c.compareTo(first.getElement()) <= 0) //multiple in list add to start
                   node.setNext(first);
                   first = node;
              }else if(c.compareTo(last.getElement()) > 0) //multiple in list add to end
                   last.setNext(node);
                   last = node;
              }else
                   first.add(node);
              count++;
         public Comparable remove(Comparable target) throws EmptyStackException,NoSuchElementException
              if(isEmpty())
                   throw new EmptyStackException();
              boolean found = false;
              LinearNode previous = null;
              LinearNode current = first;
              while(current != null && !found)
                   if(target.equals(current.getElement()))
                             found = true;
                   else{
                        previous = current;
                        current = current.getNext();
              if(!found)
                   throw new NoSuchElementException();
              if(size() == 1)
                   first = last = null;
              else if (current.equals(first))
                   first = current.getNext();
                   else if(current.equals(last))
                             last = previous;
                             last.setNext(null);
                        else
                             previous.setNext(current.getNext());
              count--;
              return current.getElement();
         public boolean isEmpty()
              return count == 0;
              //return first == null;
         public String toString()
              String result = "";
              LinearNode current = first;
              while(current != null)
                   result += current.getElement();
                   current = current.getNext();
              return result;
         public int size()
              return count;
    }

    That's rather a lot of code - and much of it has nothing obvious to do with sorting strings by length. Also I can't see where you have implemented the Comparable interface.
    You are talking about java.lang.Comparable, right? In that case some class (Word?) has to be declared as "implements Comparable".
    Another way to do this is is to have an instance of Comparator that you use when you create an ordered collection like a TreeSet.
    Have you read the JavaWorld article: [http://www.javaworld.com/javaworld/jw-12-2002/jw-1227-sort.html]. It is rather old now and doesn't make any use of generics. But it gives examples of a simple collection - a list - being sorted using Collections.sort(). Both the Comparable and Comparator approaches are illustrated

  • Creating truly custom mail rule - Subject line word length?

    hey, first post... i am noting tons of spam where the subject line is one long mess consisting of junk words. There is no custom rule category allowing me to set something similar to:
    if SubjectLine has word with length >20 Junk It..
    Until Apple catches up to spammers and gives that to us, can anyone help me perhaps do this sort of thing? thanks, drew..

    i solved this myself and can be contacted privately for the answer..

  • Sort ArrayList by length

    I need to remove the string(s) with the least number of letters from an ArrayList.
    How can I sort the ArrayList by the length of the strings contained in it?

    Why would you need to?
    1.5 (you should be using an ArrayList<String>)
    list.get(i).length();Earlier (without generics)
    ((String)list.get(i)).length();This is of course irrelevent to impelementing a
    simple Comparator and passing it to Collections.Or
    list.get(i).toString().length();
    Or
    new StringBuilder(list.get(i).toString().toCharArray()).toString();

  • Metadata Browser, sort by FOCAL LENGTH

    I'd like to see the option to sort images by focal length, in addition to the by aperture, and by shutter speed.
    //Svien

    In addition, please add the capability sort images in grid view by any meta data item recognized by LR, i.e.: camera model, camera serial number, etc.
    In environments where LR is used to manage images from a variety of shooters and cameras it is extremely useful to be able to sort by meta data via the view:sort order dialog.
    In a high speed workflow environment the work-around of filtering by date range and selecting meta data filters is not desirable.

  • Sort songs by length

    Recently, the ability to sort songs in a playlist by length has been removed. I want it to be put back in because I found it very useful.

    Updated: 2015-08-02Hello!
    This option is still available. I'm taking it you're on the desktop app: just increase the window size of the Spotify application or maximize it. The sorting option should then pop up again. ;)

  • Sort string by length

    Hi Everyone
    I have a set of data
    qqq
    adadada as
    aas a
    asada
    adasdas adada
    now I need a formula which can sort these strings according to the length. So the longest string will come at the top. I would really appreciate if anyone could help me with it.
    Thanks

    If you need to code this yourself then simply implement a sorting algorithm, get the two lengths and swap the Strings if necessary.
    If you can utilise the sort method written in Collections class, then you will need to write your own Comparator.
    Read about these classes and try it yourself. If you are still having trouble come back and ask a specific question.

  • Sorting by pixel length/width in Aperture 2.0

    I have a smart album for images to be submitted to a stock agency. This agency requires that the long edge of an image be a minimum of a certain number of pixels. How can I sort out the images that meet those requirements from those that need to be enlarged to meet the requirement? I tried sorting using pixel size, but I'm not sure what "pixel size" means to Aperture exactly, as some images that have clearly larger pixel dimensions get listed in the middle of ones that have smaller dimensions.
    Any ideas?

    Edward Tobin wrote:
    ...Once I return home I upload my photographs into a new project in Aperture for editing. When I am happy with the editing I assign metadata to them to describe the location and keywords.
    IMO no, the first step us to assign metadata that applies to all images in the batch during the import to the entire batch of images. Of course individual images can later get image-specific metadata.
    ...So it looks like projects are not for long term organization.
    IMO projects are very much for long term organization in that each project can fully stand alone. However also IMO good keywording far transcends project organization. E.g. "Tibet 2008" is a project that stands alone, but the keyword "flowers" crosses all projects to present all flowers ever keyworded.
    -Allen Wicks

  • Subject line of length 100 to 150 char

    Hello Gurus,
    I have written a report to send mail from sap to external user.
    i have written the code by using the function module SO_DOCUMENT_SEND_API1. In SOST tcode the document title description should be of 100 to 150 char but i am able to display only 50. Is there any other FM which accepts more subject in the TITLE.
    Can anybody please help me out in this issue.
    This is very urgent. I will reward you with points.
    Thanks,
    Karan

    hi check this report
    REPORT  ZMAIL.
    TABLES: ekko.
    PARAMETERS: p_email   TYPE somlreci1-receiver .
    TYPES: BEGIN OF t_ekpo,
      ebeln TYPE ekpo-ebeln,
      ebelp TYPE ekpo-ebelp,
      aedat TYPE ekpo-aedat,
      matnr TYPE ekpo-matnr,
    END OF t_ekpo.
    DATA: it_ekpo TYPE STANDARD TABLE OF t_ekpo INITIAL SIZE 0,
          wa_ekpo TYPE t_ekpo.
    TYPES: BEGIN OF t_charekpo,
      ebeln(10) TYPE c,
      ebelp(5)  TYPE c,
      aedat(8)  TYPE c,
      matnr(18) TYPE c,
    END OF t_charekpo.
    DATA: wa_charekpo TYPE t_charekpo.
    DATA:   it_message TYPE STANDARD TABLE OF solisti1 INITIAL SIZE 0
                    WITH HEADER LINE.
    DATA:   it_attach TYPE STANDARD TABLE OF solisti1 INITIAL SIZE 0
                    WITH HEADER LINE.
    DATA:   t_packing_list LIKE sopcklsti1 OCCURS 0 WITH HEADER LINE,
            t_contents LIKE solisti1 OCCURS 0 WITH HEADER LINE,
            t_receivers LIKE somlreci1 OCCURS 0 WITH HEADER LINE,
            t_attachment LIKE solisti1 OCCURS 0 WITH HEADER LINE,
            t_object_header LIKE solisti1 OCCURS 0 WITH HEADER LINE,
            w_cnt TYPE i,
            w_sent_all(1) TYPE c,
            w_doc_data LIKE sodocchgi1,
            gd_error    TYPE sy-subrc,
            gd_reciever TYPE sy-subrc.
    *START_OF_SELECTION
    START-OF-SELECTION.
      Retrieve sample data from table ekpo
      PERFORM data_retrieval.
      Populate table with detaisl to be entered into .xls file
      PERFORM build_xls_data_table.
    *END-OF-SELECTION
    END-OF-SELECTION.
    Populate message body text
      perform populate_email_message_body.
    Send file by email as .xls speadsheet
      PERFORM send_file_as_email_attachment
                                   tables it_message
                                          it_attach
                                    using p_email
                                          'Example .xls documnet attachment'
                                          'XLS'
                                          'filename'
                                 changing gd_error
                                          gd_reciever.
      Instructs mail send program for SAPCONNECT to send email(rsconn01)
      PERFORM initiate_mail_execute_program.
    *&      Form  DATA_RETRIEVAL
          Retrieve data form EKPO table and populate itab it_ekko
    FORM data_retrieval.
      SELECT ebeln ebelp aedat matnr
       UP TO 10 ROWS
        FROM ekpo
        INTO TABLE it_ekpo.
    ENDFORM.                    " DATA_RETRIEVAL
    *&      Form  BUILD_XLS_DATA_TABLE
          Build data table for .xls document
    FORM build_xls_data_table.
      data: ld_store(50) type c.  "Leading zeros
      CONSTANTS: con_cret(5) TYPE c VALUE '0D',  "OK for non Unicode
                 con_tab(5) TYPE c VALUE '09'.   "OK for non Unicode
    *If you have Unicode check active in program attributes thnen you will
    *need to declare constants as follows
    *class cl_abap_char_utilities definition load.
    *constants:
       con_tab  type c value cl_abap_char_utilities=>HORIZONTAL_TAB,
       con_cret type c value cl_abap_char_utilities=>CR_LF.
      CONCATENATE 'EBELN' 'EBELP' 'AEDAT' 'MATNR' INTO it_attach SEPARATED BY con_tab.
      CONCATENATE con_cret it_attach  INTO it_attach.
      APPEND  it_attach.
      LOOP AT it_ekpo INTO wa_charekpo.
    *Modification to retain leading zeros
      inserts code for excell REPLACE command into ld_store
      =REPLACE("00100",1,5,"00100")
        concatenate '=REPLACE("' wa_charekpo-ebelp '",1,5,"'
                                 wa_charekpo-ebelp '")' into ld_store .
      concatenate ld_store into .xls file instead of actual value(ebelp)
        CONCATENATE wa_charekpo-ebeln ld_store  wa_charekpo-aedat wa_charekpo-matnr  INTO it_attach SEPARATED BY con_tab.
        CONCATENATE con_cret it_attach  INTO it_attach.
        APPEND  it_attach.
      ENDLOOP.
    ENDFORM.                    " BUILD_XLS_DATA_TABLE
    *&      Form  SEND_FILE_AS_EMAIL_ATTACHMENT
          Send email
    FORM send_file_as_email_attachment tables pit_message
                                              pit_attach
                                        using p_email
                                              p_mtitle
                                              p_format
                                              p_filename
                                              p_attdescription
                                              p_sender_address
                                              p_sender_addres_type
                                     changing p_error
                                              p_reciever.
      DATA: ld_error    TYPE sy-subrc,
            ld_reciever TYPE sy-subrc,
            ld_mtitle LIKE sodocchgi1-obj_descr,
            ld_email LIKE  somlreci1-receiver,
            ld_format TYPE  so_obj_tp ,
            ld_attdescription TYPE  so_obj_nam ,
            ld_attfilename TYPE  so_obj_des ,
            ld_sender_address LIKE  soextreci1-receiver,
            ld_sender_address_type LIKE  soextreci1-adr_typ,
            ld_receiver LIKE  sy-subrc.
      ld_email   = p_email.
      ld_mtitle = p_mtitle.
      ld_format              = p_format.
      ld_attdescription      = p_attdescription.
      ld_attfilename         = p_filename.
      ld_sender_address      = p_sender_address.
      ld_sender_address_type = p_sender_addres_type.
    Fill the document data.
      w_doc_data-doc_size = 1.
    Populate the subject/generic message attributes
      w_doc_data-obj_langu = sy-langu.
      w_doc_data-obj_name  = 'SAPRPT'.
      w_doc_data-obj_descr = ld_mtitle .
      w_doc_data-sensitivty = 'F'.
    Fill the document data and get size of attachment
      CLEAR w_doc_data.
      READ TABLE it_attach INDEX w_cnt.
      w_doc_data-doc_size =
         ( w_cnt - 1 ) * 255 + STRLEN( it_attach ).
      w_doc_data-obj_langu  = sy-langu.
      w_doc_data-obj_name   = 'SAPRPT'.
      w_doc_data-obj_descr  = ld_mtitle.
      w_doc_data-sensitivty = 'F'.
      CLEAR t_attachment.
      REFRESH t_attachment.
      t_attachment[] = pit_attach[].
    Describe the body of the message
      CLEAR t_packing_list.
      REFRESH t_packing_list.
      t_packing_list-transf_bin = space.
      t_packing_list-head_start = 1.
      t_packing_list-head_num = 0.
      t_packing_list-body_start = 1.
      DESCRIBE TABLE it_message LINES t_packing_list-body_num.
      t_packing_list-doc_type = 'RAW'.
      APPEND t_packing_list.
    Create attachment notification
      t_packing_list-transf_bin = 'X'.
      t_packing_list-head_start = 1.
      t_packing_list-head_num   = 1.
      t_packing_list-body_start = 1.
      DESCRIBE TABLE t_attachment LINES t_packing_list-body_num.
      t_packing_list-doc_type   =  ld_format.
      t_packing_list-obj_descr  =  ld_attdescription.
      t_packing_list-obj_name   =  ld_attfilename.
      t_packing_list-doc_size   =  t_packing_list-body_num * 255.
      APPEND t_packing_list.
    Add the recipients email address
      CLEAR t_receivers.
      REFRESH t_receivers.
      t_receivers-receiver = ld_email.
      t_receivers-rec_type = 'U'.
      t_receivers-com_type = 'INT'.
      t_receivers-notif_del = 'X'.
      t_receivers-notif_ndel = 'X'.
      APPEND t_receivers.
      CALL FUNCTION 'SO_DOCUMENT_SEND_API1'
           EXPORTING
                document_data              = w_doc_data
                put_in_outbox              = 'X'
                sender_address             = ld_sender_address
                sender_address_type        = ld_sender_address_type
                commit_work                = 'X'
           IMPORTING
                sent_to_all                = w_sent_all
           TABLES
                packing_list               = t_packing_list
                contents_bin               = t_attachment
                contents_txt               = it_message
                receivers                  = t_receivers
           EXCEPTIONS
                too_many_receivers         = 1
                document_not_sent          = 2
                document_type_not_exist    = 3
                operation_no_authorization = 4
                parameter_error            = 5
                x_error                    = 6
                enqueue_error              = 7
                OTHERS                     = 8.
    Populate zerror return code
      ld_error = sy-subrc.
    Populate zreceiver return code
      LOOP AT t_receivers.
        ld_receiver = t_receivers-retrn_code.
      ENDLOOP.
    ENDFORM.
    *&      Form  INITIATE_MAIL_EXECUTE_PROGRAM
          Instructs mail send program for SAPCONNECT to send email.
    FORM initiate_mail_execute_program.
      WAIT UP TO 2 SECONDS.
      SUBMIT rsconn01 WITH mode = 'INT'
                    WITH output = 'X'
                    AND RETURN.
    ENDFORM.                    " INITIATE_MAIL_EXECUTE_PROGRAM
    *&      Form  POPULATE_EMAIL_MESSAGE_BODY
           Populate message body text
    form populate_email_message_body.
      REFRESH it_message.
      it_message = 'Please find attached a list test ekpo records'.
      APPEND it_message.
    endform.                    " POPULATE_EMAIL_MESSAGE_BODY
    regards,
    venkat appikonda

  • Customer statement line item sorting

    Hello SAP Gurus,
    We use a customer statement which has SAP delivered program and 'z'type form, but our requirement is to sort the line items inside the statement.
    I tried using o7s6 - Line item Corresponding sort variant (SPRO>F/A>F/A Global Settings-->Correspondence)in that how would I create a sorting variant that will sort line items based on due date.
    And also I believe some configuration need to be done in variant for program i.e., SE38--> give the program name and execute (F8) --> in side this there are options to sorting by due date but I was not able to achieve what I want.
    Can anyone please help me with this.
    Thanks
    Kishore
    Message was edited by:
            kishore

    Hello
    follow the link and you could get more info
    http://help.sap.com/saphelp_erp2005vp/helpdata/en/01/a9c1cb455711d182b40000e829fbfe/frameset.htm
    Editing Line Items
    You can edit line items for a payment or an exception list at a second list level. You can use the following functions to help you edit line items:
    Sort
    Search
    Change line layout
    To edit line items of a payment, double-click the desired payment line.
    The system then displays the open items of this payment on another screen.
    Sorting Line Items
    To sort open items, choose Edit ® Sort. This brings up an additional window where you can sort the line items according to four criteria and define a sequence (see "Sorting Payments" in Editing Payments).
    Searching for Line Items
    To search for particular open items, choose Edit ® Find. Select a search criterion and enter the desired values or value ranges (see "Searching for Payments" in Editing Payments).
    Changing the Line Layout
    To change the line layout, choose Settings ® Line Layout, and select the required line layout variant. There are four variants delivered with the standard system.
    The standard setting for the sort, find, change line layout, and display totals functions depends on your system configuration. You can change it in Customizing.

  • Change sort order in line graph

    Sorry, my mistake !
    In one of the ColLabels i had placed the xsl:sort line ABOVE the xsl:for-each.
    So, now it is working.
    In a line graph I need to change the sort order of the elements in my XML file.
    I need the elements to be sorted by month number, so that january comes first, then february etc.
    I have an element in the XML file called DATE which has the format 'YYYYMMDD'
    I tried first to change the sort command for the Label.
    <ColLabels>
    <xsl:for-each select=".//XX_ROW" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:sort select="substring(DATE,5,2)"/>
    That worked fine, the label values are resorted as I wanted.
    Of course, I also have to set the same sort order for the data values.
    So I did that in the same way :
    <RowData>
    <xsl:for-each select=".//XX_ROW" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:sort select="substring(DATE,5,2)"/>
    But, to my surprise, I got an error :
    Caused by: oracle.xdo.parser.v2.XSLException: <Line 70, Column 45>:
    XML-22047: (Error) Invalid instantiation of 'xsl:sort' in 'RowData' context.
    Does anybody understand why this was not possible ?
    Is there another syntax for sorting in the RowData ?
    What's the use of being able to sort the X axis lable, if I am not able to sort the data ?
    Edited by: user792912 on 2011-maj-30 05:11

    This was an error I had made in the graph code.
    The xsl:sort line must be placed AFTER the xsl:for-each !

  • Reading specific lines in a file

    hI
    i need to write a program which has a file name a.txt the contents in the file is
    SELECT DISTINCT D.MENUNAME, D.MENULABEL, D.MENUSEP, D.MENUORDER FROM PSMENUDEFN D, PSAUTHITEM A, PSOPRCLS C WHERE D.INSTALLED = 1 AND D.MENUGROUP = :1** AND D.MENUNAME = A.MENUNAME AND A.AUTHORIZEDACTIONS > 0 AND A.CLASSID = C.OPRCLASS AND C.OPRID = :2** ORDER BY D.MENUORDER, D.MENUNAME
    Bind-1 length=21 value=&Administer Workforce
    Bind-2 length=6 value=NLWAJP
    I need to read the file in such a way that in the SQL statement in the place of ":1" I need to get Bind-1 value i.e., &Administer Workforce and same with :2 I need to get Bind 2 value NLWAJP
    Output must be like this
    SELECT DISTINCT D.MENUNAME, D.MENULABEL, D.MENUSEP, D.MENUORDER FROM PSMENUDEFN D, PSAUTHITEM A, PSOPRCLS C WHERE D.INSTALLED = 1 AND D.MENUGROUP = &Adminster Workforce AND D.MENUNAME = A.MENUNAME AND A.AUTHORIZEDACTIONS > 0 AND A.CLASSID = C.OPRCLASS AND C.OPRID = NLWAJP ORDER BY D.MENUORDER, D.MENUNAME

    thomas.behr wrote:
    Read in your text file line by line, then replace \*XXX\*:Y** with the appropriate value using regular expressions.
    Phani532 wrote:The above answers doesnot answer my question....
    I am putting my question in refined format...Wrong. import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.StringReader;
    import java.util.List;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.Map;
    import java.util.HashMap;
    import java.util.regex.Pattern;
    import java.util.regex.Matcher;
    public class Test {
      private static final String DEFAULT_TEXT =
      "SELECT DISTINCT D.MENUNAME, D.MENULABEL, D.MENUSEP, D.MENUORDER FROM PSMENUDEFN D, PSAUTHITEM A, PSOPRCLS C WHERE D.INSTALLED = 1 AND *D.MENUGROUP = *:1** AND D.MENUNAME = A.MENUNAME AND A.AUTHORIZEDACTIONS > 0 AND A.CLASSID = C.OPRCLASS AND *C.OPRID = *:2** ORDER BY D.MENUORDER, D.MENUNAME\n" +
      "Bind-1 length=21 value=&Administer Workforce\n" +
      "Bind-2 length=6 value=NLWAJP";
      public static void main( String[] args ) {
        final List<String> lines = new ArrayList<String>();
        try {
          BufferedReader br = null;
          try {
            br = new BufferedReader(new StringReader(DEFAULT_TEXT));
            String line;
            while ((line = br.readLine()) != null) {
              lines.add(line);
          } finally {
            if (br != null) {
              br.close();
        } catch (IOException ioe) {
          lines.clear();
          ioe.printStackTrace();
        if (!lines.isEmpty()) {
          Collections.sort(lines, new Comparator<String>() {
            public int compare( final String s1, final String s2 ) {
              if (s1.startsWith("Bind-")) {
                if (s2.startsWith("Bind-")) {
                  return s1.compareTo(s2);
                } else {
                  return -1;
              } else {
                if (s2.startsWith("Bind-")) {
                  return 1;
                } else {
                  return s1.compareTo(s2);
          final Map<String, String> parameters = new HashMap<String, String>();
          for (String line : lines) {
            if (line.startsWith("Bind-")) {
              parameters.put(line.substring(5, line.indexOf(' ')), line.substring(line.indexOf("value=") + 6));
            } else if (line.startsWith("SELECT ")) {
              final Matcher matcher = Pattern.compile("\\*(.*?)\\*:([\\d]*?)\\*\\*").matcher(line);
              final StringBuilder sb = new StringBuilder();
              int last = 0;
              while (matcher.find()) {
                final int idx = matcher.start();
                if (idx > last) {
                  sb.append(line.substring(last, idx));
                sb.append(matcher.group(1));
                sb.append(parameters.get(matcher.group(2)));
                last = matcher.end();
              if (last < line.length()) {
                sb.append(line.substring(last));
              System.out.println(sb.toString());
    }(Lucky you, I'm feeling generous - and eager to code.)

Maybe you are looking for

  • Cisco Jabber for Android on a Samsung Galaxy Xcover (GT-S5690)

    Hello there, Yesterday we installed the Cisco Jabber client for Android on the Samsung Galaxy Xcover (GT-S5690) phone. First we had some issue's with one-way voice, but suddenly this problem was occured. Another problem, which is still there, is when

  • Error message-itunes detected a problem with av

    itunes has detected a problem with your audio config, av plyback may not opperate properly. i get this message when i open itunes. followed other instructions to uninstall quicktime and reinstall. can't play music files or cd's. hit play and nothing

  • Contacts Lost

    I have given my niece my old iPhone 4 and she has deleted my contacts on my iPhone 5 how can I restore and stop this happening again

  • Writing/reading password protected zip/gzip files

    Hello All, is there anyway in java that i can write/read password protected zip/gzip files?? thanks in advance.

  • How to check the checkboxes that are dynamically displayed in the browser

    Hi Here the requirement is ,I am dynamically diaplaying the text boxes based on the data captured from the database.Here depending upon the number characters in Database,related that much of checkboxes will display.How can i provide Javascript client