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

transforming the format of my file

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Hi there,

I have a file of 600 words that looks like this:

street
walk
seven
ghost
...

Now I want to transform this file to several smaller files with the words on one line, so:

street walk seven ghost ...

It would be nice if I could specify in my command line how many words there are in the smaller files, so length=20 would give me 30 files of twenty words.
Maybe you can help me out?

 
Hi rextach,

Try this program.
Code:
{
  if (NR%len == 1) {
    if (NR>1) {
      print "" > fn
      close(fn)
    }
    ix++
    fn = "file" ix
  }
  printf $0 " " > fn
}
END {
   print > fn
}
Put it in a file, s.awk say, and run it by entering
Code:
awk -f s.awk -v len=20 your-file
It will create files called file1, file2, file3, etc.

Hope this helps. CaKiwi
 
Thanx for the help CaKiwi but would you mind explaining your script because I don't really understand it.

Rextach
 
Hi there,

how can I change CaKiwi's script so that my files will still be of length 20 but the second file begins with the last word of file 1, the third with the last word of file 2, etc...?

rextach
 
Hi rextach,

Here's an explanation. NR contains the current record number so NR %len is equal to 1 for then 1st, 21st, 41st record (assuming len = 20) when we want to close the old file and create the name for a new one. printf $0 " " > fn prints the current lne and a space (but not a line feed) to the current file. print "" > fn prints a line feed at the end of the record. To have the last word in each file repeated in the next file, make the following (untested) change.
[tt]
if (NR%(len-1) == 1) {
if (NR>1) {
print > fn
[/tt]
Hope this helps. CaKiwi
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top