Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Join lines in a file 2

Status
Not open for further replies.

mrmac228

IS-IT--Management
May 27, 2003
255
0
0
GB
I have a file where I need to join consecutive lines. The twist is that the number of lines to join together varies. An example file is:

TAG ,
Attribute1 ,
Attribute2 ,
Attribute3 ,
TAG ,
Attribute1 ,
TAG ,
Attribute1 ,
Attribute2 ,
Attribute3 ,

The TAG is consistent ( i.e. the same string) and I need to join all the attribute lines to the TAG line for each occurence of TAG as below.

TAG ,Attribute1 ,Attribute2 ,Attribute3 ,
TAG ,Attribute1 ,
TAG ,Attribute1 ,Attribute2 ,Attribute3 ,

I've been trying with sed and have got this script

/TAG/,/Attribute/{
/^TAG/N;s/\n/ /g
}
So I'm defining the block of text I want to operate on and then keep adding to the multiline and change carriage returns to space. This works up to a point in that the entries with 1 attribute is joined ok, however the multiple attribute lines only joins the first attribute. i.e.

TAG ,Attribute1 ,
Attribute2 ,
Attribute3 ,
TAG ,Attribute1 ,
TAG ,Attribute1 ,
Attribute2 ,
Attribute3 ,

Any clues as to what this final step should be would be greatly appreciated.


I love deadlines. I like the whooshing sound they make as they fly by - Douglas Adams
 
It's just like the thing, you post for help, change the way you think about how your doing stuff and lo and behold it works.

The solution I have is:

# Get all non TAG lines
# Put them in the Hold space
# Delete from the pattern space
# Swap the hold and pattern space
# change the carriage returns for space

/^TAG/!{
H
d
}
x
s/\n/ /g

And this gives me the solution.

Hope I haven't wasted anyones time.

Ken

I love deadlines. I like the whooshing sound they make as they fly by - Douglas Adams
 
Not a sed solution, but how about something like this:

Code:
NEWLINE=""
while read LINE COMMA
do
  if [[ $LINE = "TAG" ]]
   then
     if [[ $NEWLINE != "" ]]; then echo $NEWLINE >> some_new.file; fi
     NEWLINE="$LINE $COMMA"
   else
     NEWLINE="$NEWLINE $LINE $COMMA"
   fi
done < some.file
echo $NEWLINE >> some_new.file

Add a little color to your PUTTY terminal: faq52-6627
 
Another way with awk
Code:
awk '
   /^TAG/ {if (tag) print tag; tag = "" }
          { tag = tag $0 }
   END    {if (tag) print tag }
    ' inputfile

Jean-Pierre.
 
Thanks guys both these solutions work too.

Have a star!

I love deadlines. I like the whooshing sound they make as they fly by - Douglas Adams
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top