Find the answer to your Linux question:
Results 1 to 4 of 4
Hello ! I have been searching for a while on how to do that... But I am not really used to Sed, so it tkaes too much time for me ...
  1. #1
    Just Joined!
    Join Date
    May 2009
    Posts
    2

    joining lines with sed

    Hello !

    I have been searching for a while on how to do that... But I am not really used to Sed, so it tkaes too much time for me to find out. I hope you could help me

    I give an example of text I have :

    (10)This is a sequence of data..
    which continues in this line
    and in this one also
    (11)This a new sequence of data in one line
    (12)This is new sequence of data in 3 lines
    it continues here
    and here
    I would like to join the lines of a same sequence number like the following, using commas to separate the joined lines :
    (10)This is a sequence of data..,which continues in this line,and in this one also
    (11)This a new sequence of data in one line
    (12)This is new sequence of data in 3 lines,it continues here,and here
    The data file always contains either sequences of one line or of 3 lines.

    I thought of using the Sed command with regular expressions considering to append every 3 lines to the pattern space (using N), and if this latter matches the pattern of "block of 3 lines that should be joined in one" then it subsitutes with "/\1,\2,\3/" where 1, 2 and 3 represent the 3 lines of a same sequence. If it doesnt match, the line is replaced by itself.

    At the moment I have something like the following, and I should add the "N" command to read 2 following lines and check if they correspond to a same sequence number, then replace with the lines joined, if not then keep it as it is..

    Code:
    sed -r 's/(\([0-9]*\)[^\(\n\([0-9]*\)\)]*)/\1,\2/'
    I hope its clear

    Thanks for your help !

  2. #2
    Just Joined!
    Join Date
    Jul 2009
    Posts
    58
    It's a lot easier to do it in two steps:

    # awk -v RS= '{$2=""}1' foo | sed -r 's/\(/\n\(/g'

    Where foo contains your lines. The space after the = sign is important as is the name of the variable.

  3. #3
    Linux User
    Join Date
    Aug 2006
    Posts
    458
    see here (example 16) for awk one liner. substitute "pattern" for ^\(

  4. #4
    Just Joined!
    Join Date
    Jul 2009
    Posts
    58
    I just realized that he wanted to insert commas where the line breaks where
    so for the example ghostdog provided you can just replace "%s" with "%s, ".

    It would be harder to do it in mine.

    But both are going to have issues. Mine will not have the comma, but will terminate the line. The example awk will not have a final \r or \n at the end of the last line, so you'll have to terminate the line afterward (if need be).

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...