1

I am trying to write a loop that reads the text file and prints all the lines that is starting with (t:).the loop should print upto 200 lines that contains (t:) word to output file. the remaining words starting with (t:) should print in other output.file how to do this?

Basically what the script should do is it should not print more than 200 lines. if there more than 200 lines the remaining lines should printed in another output file.

for example

the text file contains

(t:) should print in other output.
sfsfsaff
(t:) blablabla
(t:) should print in other output.
(t:) blablalbalbalbalba
 blalblabalbalbab
balbalbablaba
balbablalbalba
balbalbalbab
ablablalbab.
(t:) blablabla
(t:) blablabla

output.txt

    (t:) should print in other output.
    (t:) blablabla
    (t:) should print in other output.
    (t:) blablalbalbalbalba
    (t:) blablabla
    (t:) blablabla
2
  • 2
    Please try to clarify your question. Where do the lines you want to print come from? Do you want to print the lines that are beginning with 't:' or do you want to print lines adding the 't:' at the beginning. Commented May 6, 2013 at 8:24
  • 1
    give an example input file and the desired output for that. 3 or 4 lines would be ok Commented May 6, 2013 at 8:30

3 Answers 3

3

You don't even need a loop for that. You can use the existing tools and combine them in the good ol' unix tradition:

cat inputfile | grep "^t\:" | split -l 200

Of course you can still do modifications like filter out the leading t: if it is not required in the output...

For more details just read the man pages for the grep and the split command...

Sign up to request clarification or add additional context in comments.

2 Comments

I knew there is a more elegant solution to this. :) However this works only if the entries are in the rigt order.
Code golf: grep "^(\t:" inputfile | split -l 200
1

use the following awk script:

awk '/^\(t:\)/{if(++c <= 200){print >> "outfile1"}else{print >> "outfile2"}}' infile

Comments

0
>file1; >file2; N=0; cat myfile | while read f; do T=`echo "$f" | grep "^t:"`; if [ "$T"x = x ] then; N=`expr $N + 1`; fi; if [ "$N" -lt 200 ] then; echo "$f" >> file1; else; echo >> file2; fi; done

This works in virtually any shell and is not relying on bash as the shell.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.