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
- Use TextReader (and the ReadLine method) to retrieve each line.
- Use String.StartsWith (Better than regex, less footprint, and does the same thing you're trying to accomplish, as far as I can tell)
- Use TextWriter (and the WriteLine method) to store your results.
PHP
- Use file to read the original and place each line in an array
- Use strncmp to see if the string begins with your "ABC:" match.
- 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.
精彩评论