Reputation: 11
I would like to write a script that reshapes a text file that looks like this:
word1
word2
word3
word4
word5
word6
word7
word8
word9
word10
word11
word12
...
into this:
word1 word2 word3 word4
word5 word6 word7 word8
word9 word10 word11 word12
...
Does anyone know of an easy way to do so?
Upvotes: 1
Views: 172
Reputation: 29854
perl -l -00 -aF/\s*\n\s*/ -ne 'print "@F"' /source/file > /dest/file
Explanation (using TLP's suggestions)
print
act like say
.@F
Upvotes: 1
Reputation: 67910
perl -i.bak -pwe 's/\S\s*\K\n$/ /' input.txt
-i.bak
saves a backup in input.txt.bak
-p
puts a while (<>) loop around your script\K
escape means "keep anything before this".Another option:
perl -i.bak -lpwe 'BEGIN { $/="" }; s/\n/ /g' input.txt
Using paragraph mode in the BEGIN block, and following each print with a newline with -l
Upvotes: 2
Reputation: 7526
It appears that your groups are "paragraphs" so read them as such; split the words on whitespace; rejoin them using a single space (blank) and print the result:
#!/usr/bin/env perl
use strict;
use warnings;
local $/ = '';
my @words;
while (<DATA>) {
@words = split;
print join q( ), @words, "\n";
@words = ();
}
__DATA__
word1
word2
word3
word4
word5
word6
word7
word8
word9
word10
word11
word12
Upvotes: 1