Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a log file as follows

 [10-10-2013 10.10.10.333 CDF] Column2 Column3
 [11-10-2013 10.10.10.333 CDF] Column2 Column3

If I want to split the above log file by spaces first, it will split up to date first and then time and CDF and so on.

Is there any possible way to get whole first column [10-10-2013 10.10.10.333 CDF] as one column and then work on it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
198 views
Welcome To Ask or Share your Answers For Others

1 Answer

Based on the info you've given us, you can just take a substring from 0 to the index of the ].

string ExtractFirstColumn(line) {
    int index = line.IndexOf("]");
    string firstColumn = line.Substring(0, index + 1);
    return firstColumn;
}

That will give you the whole first column, as you asked for. You would then do this for each line. Then, if these are all in a single file, you can say:

var lines = File.ReadLines(log);
var firstColumns = lines.Select(line => ExtractFirstColumn(line));

Then, if you need to split the first column, you can split on ' ':

var tokens = firstColumn.Split(' ');
// tokens[0].Remove("[") is the data
// tokens[1] is the time
// tokens[2].Remove("]") is "CDF"

If you need more than the first column, as you're now indicating in your comments1, you'll have to move a little differently:

string[] ExtractColumns(string line) {
    int index = line.IndexOf("]");
    string firstColumn = line.Substring(0, index + 1);
    string[] lastTwoColumns = line.Substring(index + 2).Split(' ');
    return new string[] { firstColumn, lastTwoColumns[1], lastTwoColumns[2] };
}

I'm only going off the two examples you've given us, but I'd start with this very simple, maintainable approach absent new information.

1: This is why the guidelines for how to ask a question say to be specific.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...