1

I have a cricket commentary like -

0.3
Richardson to RG Sharma, 2 runs, gentle, non-swinging length ball on off, Rohit seeks to pick it up. Hit high on the bat and spooned over the returning Mitch Marsh at midwicket
0.4
Richardson to RG Sharma, 1 run, banged in short, controlled pull to long leg

What I want to do is join the n.n lines with the following lines, replacing newlines with spaces. Then, I want to delete everything from the second comma to the end on each line, so the output from the input above should be:

0.3 Richardson to RG Sharma, 2 runs
0.4 Richardson to RG Sharma, 1 run

-- Edit -- I used [0-9]"\n"[A-Z] to match the newline but I have trouble reproducing the exact number and character that was matched. Also for deleting everything after 2 commas, I tried parameter expansion but I could only get it to work for deleting after a single comma.

4
  • Show us what you tried. How do you expect us to point out where you went wrong without that?
    – Anthon
    Feb 8, 2016 at 3:19
  • I used [0-9]"\n"[A-Z] but I have trouble reproducing the exact number and character that was matched. Also for deleting everything after 2 commas, I tried parameter expansion but I could only get it to work for deleting after a single comma.
    – Naman Jain
    Feb 8, 2016 at 3:27
  • What is your expected output? Its hard to understand what you have said in words..
    – heemayl
    Feb 8, 2016 at 3:32
  • Wow, @Michael Homer It does the job perfectly.
    – Naman Jain
    Feb 8, 2016 at 3:47

2 Answers 2

3

You can use sed:

sed -ne '/^[0-9][0-9]*\.[0-6]/ { N; s/\n/ /; s/^\([^,]*,[^,]*\),.*$/\1/; p; }' < data

This processes a file called data, suppressing printing unless asked for (-n) and executing the sed program in quotes.

That program selects lines starting with one or more digits, a ., and a digit 0-6, and then runs the part in {} for those lines. The N command reads the next line in as well, with a newline in between. The first s/// replaces that newline with a space.

The second matches the new single line up to the second comma and replaces the whole line with just that first part. It captures a \( group \) with some string of non-comma characters, a comma, and some further string of non-comma characters, all followed by a comma and any text .* to the end of the line $.

The final p prints out the resulting line. All other lines of input are ignored.

0

An alternative solution in AWK:

awk -v FS="," '/^[0-9]/{line=$0;getline; line=line" "$1", "$2 ;print line}' file

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .