0

I have one text file which contains some records like below,

100,a
b
c
101,d,e
f
102,g
103,h
104,i
j
k

so,some rows start with number,some rows start with string ,and I want to merge rows which rows are order by number and merge rows like below:

100,a,b,c
101,d,e,f
102,g
103,h
104,i,j,k

How can I use awk to do this ? Thanks

1
  • 3
    SO is not a code writing service; you're expected to show your effort (eg, research, code); consider reviewing how do I ask a good question and then come back and update the question accordingly; in particular, show the code you've tried and the (wrong) output generated by your code Commented Jul 22, 2022 at 15:57

1 Answer 1

1

You can do something like:

awk '/^[0-9]/{if(buf){print buf};buf=$0}/^[a-zA-Z]/{buf=buf","$0}END{print buf}' yourfile.txt

This will

  1. Check if the current line starts with a number /^[0-9]/
  • If so then it will print out what is stored in variable buf if that variable has some value in it if (buf){print buf}
  • It will then reset the variable buf to the value of the current line buf=$0
  1. If the current line starts with a letter /^[a-zA-Z]/
  • Then it will add the current line to the value in the variable buf with a comma separator buf=buf","$0
  1. Finally when it reaches the end of the file, it prints out whatever is left in the buf variable. END{print buf}
Sign up to request clarification or add additional context in comments.

1 Comment

I didn't think about it that in depth @EdMorton Is that a concern from OPs input file or some other awk eccentricity I'm not taking into account?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.