Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting long lines in bash with numbering

Tags:

regex

text

bash

sed

I'm trying to write script that partition very long text (one line) to multiple lines. The requirement is that every line must have prefixes with numbering. I tried using sed but I have problem with numbering matches. My code:

 sed -e "s/.\{4\}/part = &\\
 /g"

Input:

AAAAAAAAABBBBBBBAAAAAAABBBBBBB

Output:

part = AAAA
part = AAAA
part = ABBB
part = BBBB
part = AAAA
part = AAAB
part = BBBB
BB

Expected:

part1 = AAAA
part2 = AAAA
part3 = ABBB
part4 = BBBB
part5 = AAAA
part6 = AAAB
part7 = BBBB
part8 = BB

Additional problem is the last part that is not labeled. Is it possible to do it with sed? Or maybe any other shell tools?

like image 684
Mariusz Mączkowski Avatar asked Dec 04 '25 04:12

Mariusz Mączkowski


1 Answers

The "hard" part of that, actually splitting the input into lines, is the job that fold exists to do:

$ echo 'AAAAAAAAABBBBBBBAAAAAAABBBBBBB' |
    fold -w 4 | awk '{print "part" NR " = " $0}'
part1 = AAAA
part2 = AAAA
part3 = ABBB
part4 = BBBB
part5 = AAAA
part6 = AAAB
part7 = BBBB
part8 = BB

Using fold will make your life easier if/when your requirements change to, say, try to only split at blanks.

like image 131
Ed Morton Avatar answered Dec 07 '25 03:12

Ed Morton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!