Results 1 to 2 of 2
I'm trying to automatically add a carriage return after a certain number of words in a plain text file. I've opened the file in gedit but can't see any options ...
- 09-26-2009 #1Just Joined!
- Join Date
- Nov 2006
- Posts
- 9
Scipt to add carriage return to text after number of words
I'm trying to automatically add a carriage return after a certain number of words in a plain text file. I've opened the file in gedit but can't see any options to format it to include the current word wrap as new lines/carriage returns. So I tried writing a bash script to do the job and this is as far as I've got:
What command could I use to edit the text file? Or is there a better way to do this?Code:#!/bin/bash MaxWords=10 WordCount=$(head -3 $1 | tail -1 | wc -w) if [ $WordCount -gt $MaxWords ]; then echo "add a carriage return after 10 words" else echo "don't add a carriage return" fi
thanks
James
- 09-28-2009 #2Linux User
- Join Date
- Jan 2007
- Location
- cleveland
- Posts
- 452
interesting little problem.
strategy: first reformat text as a long list of words
separated by spaces:
tr [:cntrl:] " " <filename | tr -s " " >new.filename
this removes all newlines/formfeeds and compresses
multiple spaces to one
second, insert a newline every ten words:
awk 'BEGIN { FS=" " } {
i=1
while ( i <= NF ) {
j=1
while (j<=10) {
printf ( "%s ", $i )
i++;j++
}
}
next
}
END { print "" }' <new.filenamethe sun is new every day (heraclitus)


Reply With Quote