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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

create new lines 2

Status
Not open for further replies.

jdhahbi

Technical User
Oct 7, 2009
24
US
Hi
I would like to add new lines with the strings after the comma.
The lines in the inFile have 2 fields separated by a tab.
I would like to remove the comma from the 2d fileld and add a new line where the 1st filed is empty and the 2d field is made of the string that followed the comma.

inFile
A[tab]m,n
B[tab]x,y,z
C[tab]t,r


outFile
A[tab]m
[tab]n
B[tab]x
[tab]y
[tab]z
C[tab]t
[tab]r


Thank you for helping
Joseph
 
What have you tried and where in your code are you stuck ?
Tip: have a look at the split function.

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Code:
tmp# cat txt
A  m,n
B  x,y,z
C  t,r

tmp# cat txt | awk '{gsub(",","\n");print}' |sed 's/^[a-z]/   &/'
A  m
   n
B  x
   y
   z
C  t
   r
 
blarneyme, why not simply this ?
Code:
awk '{gsub(",","\n   ");print}' txt

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
When I tried it without using sed the output was
Code:
# awk '{gsub(",","\n");print}' txt
A m
n
B x
y
z
C t
r

Wasn't sure if the lines after the commas were supposed to be indented or not, so added the pipe to indent.
 
After looking at your post again, I see the spaces you added in awk after the newline which I didn't catch before!
 
thank you everybody. It was very helpful.
I added a tab to get the format I want
awk '{gsub(",","\n\t");print}' inFile.txt
A m
[tab]n
B x
[tab]y
[tab]z
C t
[tab]r


joseph
 
how can I get the reverse format?
For the lines that have the same first field, I want to reduce them to one line having the second field strings separated by a comma.

inFile

A[tab]x
B[tab]y
B[tab]z
C[tab]r
C[tab]s
C[tab]t
D[tab]q

outFile

A[tab]x
B[tab]y,z
C[tab]r,s,t
D[tab]q

thank you
joseph
 
Like this ?
Code:
awk 'function brk(){if(NR>1)print k"\t"substr(x,2);x="";k=$1}k!=$1{brk()}{x=x","$2}END{brk()}' inFile >outFile

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top