开发者

reading file with condition

How do i do this:

  • read a file until some condi开发者_运维技巧tion hits (like line contains /^ABC:/, for example)
  • if condition hits, then continue to read until another condition hits (like newline). and write all these lines to some other file
  • if condition doesn't hit, then do nothing.

Thanks, -Brian


.NET

  1. Use TextReader (and the ReadLine method) to retrieve each line.
  2. Use String.StartsWith (Better than regex, less footprint, and does the same thing you're trying to accomplish, as far as I can tell)
  3. Use TextWriter (and the WriteLine method) to store your results.

PHP

  1. Use file to read the original and place each line in an array
  2. Use strncmp to see if the string begins with your "ABC:" match.
  3. Use file_put_contents to place the match in to another file, noting the FILE_APPEND flag in the arguments list.

Figured I would cover two popular languages, then update when the language is determined


Bash

infile="example.in"
outfile="example.out"
reStart="^ABC"
reEnd="^DEF"
found=0

cat $infile | while read line; do
    if [[ $found == 0 ]]; then
        if [[ "$line" =~ $reStart ]]; then
            found=1
            touch $outfile
        fi
    else
        if [[ "$line" =~ $reEnd ]]; then
            found=0
        else
            echo $line >> $outfile
        fi
    fi
done

The above will write the lines from $infile between the start ($reStart) and end ($reEnd) conditions, but not the lines with the start and end conditions themselves to $outfile. A little restructuring would take care of writing the start and end lines themselves if that's what you need.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜