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

Splitting a string of 0s & 1s

Status
Not open for further replies.

planthehe

Technical User
Joined
Apr 2, 2007
Messages
1
Location
US
Hi,

I have a file of with lines of 0s & 1s. Something like this:

000111000111000111000111
001101010101110011010101
010101010101010100000001
000000000000000000011111
111111110000000111111011

I want to split each of these lines into chunks of 16 bits (If the number of bits is not exactly divisible by 16, I want to have the reminder in the next line). Something like this:

0001110001110001
11000111
0011010101011100
11010101
0101010101010101
00000001
0000000000000000
00011111
1111111100000001
11111011

Please let me know if you have any suggestions.

Thanks in advance!!
 
Assuming your text file is named "data.txt":

Code:
#!/usr/bin/perl

use strict;
use warnings;

{
	local @ARGV = ('data.txt');
	local $^I = '.bac';
	while (<>){
		s/(\d{16})(?=\d)/$1\n/ig;
		print;
	}
}

This is pulled in part from Kevin's faq on "Search and replace text in a file":

- Miller
 
PS.

You can also do this as a one-liner like so:

Code:
perl -i.bac -ne "s/(\d{16})(?=\d)/$1\n/g; print" data.txt

- Miller
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top