Home > database >  Get lines with "devices" at the end in c#
Get lines with "devices" at the end in c#

Time:08-15

Get the device list from the list below which are the lines with the last device word use C# script:


List of devices attached
adb server is out of date. killing...

  • daemon started successfully *
    AIE00202523 device
    f050354 device
    f050355 device
    AIE0020257 device
    AIE0020259 device
    f050346 device
    f050352 device
    AIE00202520 device

The resulting output will be a list: Devices


AIE00202523
f050354
f050355
AIE0020257
AIE0020259
f050346
f050352
AIE00202520

CodePudding user response:

You are trying to extract a specific word from a sentence, and in your case the word that we are trying to extract happens to be the first one.

With an assumption that the input is an array of strings, we can use split method on sentences which contain the word 'device' and get the item at the 0th index.

This is how you would do it,

List<string> inputData = new List<string>()
{
    "List of devices attached",
    "adb server is out of date. killing...",
    "daemon started successfully *",
        "AIE00202523 device",
        "f050354 device",
        "f050355 device",
        "AIE0020257 device",
        "AIE0020259 device",
        "f050346 device",
        "f050352 device",
        "AIE00202520 device"
};

Console.WriteLine("Devices");

foreach(var line in inputData)
{
    if (Regex.IsMatch(line, "device$"))
    {
        string deviceName = line.Split(' ')[0];
        Console.WriteLine(deviceName);
    }
}

CodePudding user response:

string devices_str = 
"AIE00202523 device\n"  
"f050354 device\n"  
"f050355 device\n"  
"AIE0020257 device\n"  
"AIE0020259 device\n"  
"f050346 device\n"  
"f050352 device\n"  
"AIE00202520 device\n";

devices_str = devices_str.Replace(" device", string.Empty);

string[] devices = devices_str.Split('\n');

foreach (string device in devices) {
    System.Console.WriteLine(device);
}
  • Related