Find the answer to your Linux question:
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 ...
  1. #1
    Just 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:

    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
    What command could I use to edit the text file? Or is there a better way to do this?

    thanks

    James

  2. #2
    tpl
    tpl is offline
    Linux 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.filename
    the sun is new every day (heraclitus)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...