How to get only a specific part of a Textfile

I need help only getting a specific part of one line on a text file
The text file looks something like this:
1532544950: DP CompType: 72
1532544950: DP UniqueID: BLE-F3O633NTC2RERFQ9MK90TYFGX
1532544950: DP Make: SAML21

I just need the numbers after the unique id on the second line.

Thank you for your help
Grab each line with std::string.getline(), use std::string.find() to test for the presence of "UniqueID:" and use std::string.substring to break up the string starting at the point that find() returned and ending at std::string.end(). Let us know if you need to see a sample.
Last edited on
Yea if i could see a sample that would be amazing!
If you want to access exactly the 2nd line at the 25th column:

1
2
3
4
5
    std::ifstream fin("textfile");
    std::string line;
    std::getline(fin, line);
    std::getline(fin, line);
    std::string number = line.substr(25);

If you want access the first (or all) lines that have "DP Unique ID:" in them, getting the number after that point:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ifstream fin("textfile");
    std::string line;
    while (std::getline(fin, line)) {
        size_t i = line.find("DP UniqueID:");
        if (i != line.npos) {
            std::string number = line.substr(i + 13);
            std::cout << number << '\n';
            // break; // if you only want the first matching line
        }
    }
}

Last edited on
@tpbThe only change I would make is not assuming that the Unique ID is a constant length. You're probably right, but just use end().

PS: Love that show.
PS: Love that show.

You recognized it! :-)

I'm not sure what you mean with end(). substr(i + 13) starts at 13 past the beginning of the search string and goes to the end (since there's no 2nd parameter, which would otherwise be the length parameter).
I just had a different approach mapped out in my head, I guess I didn't really look at yours.
With UNIX-like command line tools:
grep "DP UniqueID" | cut -d: -f3

Three possibilities:
grep "DP UniqueID" textfile | cut -d' '  -f4
awk '/DP UniqueID/{print $4}' textfile
sed -n 's/.*DP UniqueID: //p' textfile
"UNIX-like" ...
grep, cut, and sed are GNU tools. There is GNU version of awk.
"GNU's design is Unix-like, but differs from Unix by being free software and containing no Unix code."
grep, cut, and sed are GNU tools.
I'm 99% sure that UNIX had them first. Certainly grep and sed were in System 3 from the mid-70s and I suspect that cut was there too. So it's more accurate to say that there are GNU versions of grep, cut, sed and awk.
Find the line with UniqueID: and then use string.erase to delete the first part.

1
2
3
4
5
6
7
8
9
10
int main(int argc, char** argv) 
{
string x="1532544950: DP UniqueID: BLE-F3O633NTC2RERFQ9MK90TYFGX";
cout << x << endl;

x.erase(0,25);
cout << x << endl;

return 0;
}
Last edited on
Topic archived. No new replies allowed.