2020年8月20日 星期四

字串搜尋比較

run.sh
#!/bin/bash

str="Aug 20 10:34:45 cs2=home_ubuntu cs2_1234 Aug 20 10:34:45 cs2_1234 cs2=home_ubuntu12345"

ii=0
while true
do
    fstr=$(echo $str | awk -F" " '{print $argv0}' argv0=$ii)
    if [ -z "$fstr" ];
    then
        break
    fi  

    if [ ${fstr:0:4} = "cs2=" ];
    then
        echo $fstr
    fi  
    ii=$((ii+1))
    #echo "ii="$ii
done
$ time ./run.sh

cs2=home_ubuntu
cs2=home_ubuntu12345

real	0m0.033s
user	0m0.031s
sys	    0m0.011s
ref: how-do-i-use-shell-variables-in-an-awk-script

run.py
#!/bin/python3
import os
  
  def test():
  
      str="Aug 20 10:34:45 cs2=home_ubuntu cs2_1234 Aug 20 10:34:45 cs2_1234 cs2=home_ubuntu12345"
  
      fstr = str.split(" ")
  
      for i in fstr: 
          if "cs2=" in i:
              print(i)
  
  if __name__=='__main__':
       test()
$ time python3 ./run.py

cs2=home_ubuntu
cs2=home_ubuntu12345

real	0m0.027s
user	0m0.023s
sys 	0m0.004s

run.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char buf[128]="Aug 20 10:34:45 cs2=home_ubuntu cs2_1234 Aug 20 10:34:45 cs2_1234 cs2=home_ubuntu12345";
    char *target="cs2=";
    char *tmp;
    char *pch, *delim=" ";
    
    pch = strtok(buf,delim);
    for(; pch != NULL; ) 
    {
        tmp=strstr(pch, target);
        if(tmp != NULL)
        {
            printf("%s\n", tmp);
        }
        pch = strtok (NULL, delim);
    }
    return 0;
}
$ time ./run
cs2=home_ubuntu
cs2=home_ubuntu12345

real	0m0.001s
user	0m0.001s
sys	0m0.000s

沒有留言:

張貼留言