'String'에 해당되는 글 7건

  1. 2022.05.24 [Shell] Bash String Split - tr
  2. 2022.03.14 [Shell] Bash String Replacement.
  3. 2021.11.25 [Elasticsearch] LowLevelRestClient 를 이용한 개발 시 Json 결과 처리
  4. 2021.07.27 [Bash] 문자열 비교 예제
  5. 2020.04.20 [Bash] Bash function, array parameters, str replace 등
  6. 2014.02.13 [Java] String split 성능테스트.
  7. 2013.02.01 c++ string replace

[Shell] Bash String Split - tr

ITWeb/개발일반 2022. 5. 24. 12:38

쉘 스크립트 내부에서 문자열을 구분자를 이용해서 분해 하는 방법입니다.

IFS, read 를 이용해서 하는 방법도 있으니 찾아 보시면 되겠습니다.

 

여기서는 tr 을 이용해서 하는 방법에 대해서 가볍게 작성 합니다.

TARGET="1,2,3,4,5"
targets=($(echo $TAGET | tr "," "\n"))
targetSize=${#targets[@]}

for i in "${targets[@]}"
do
  echo $i
done

코드에서 가끔 실수 하는 부분은 

- ($(echo $TARGET | tr "," "\n")) 에서  괄호가 두 번 사용 된다는 건데 가끔 제일 앞에 괄호를 잊고 사용 할 때가 있습니다.

 

:

[Shell] Bash String Replacement.

ITWeb/개발일반 2022. 3. 14. 12:14

docker-compose.yml 내 .env 를 이용한 활용이 안되는 경우 아래 처럼 그냥 string replacement 를 통해서 처리 할 수도 있습니다.

bash 에서  array, loop, replacement 에 대한 예제로 작성해 둡니다.

 

SERVICE_NAME='{{SERVICE_NAME}}=escs'
VERSION='{{VERSION}}=8.0.0'
CONTAINER_NAME='{{CONTAINER_NAME}}=escs-c'

DOCKER_VAR=( $SERVICE_NAME $VERSION $CONTAINER_NAME )

for var in "${DOCKER_VAR[@]}"; do
    kvs=($(echo $var | tr "=" "\n"))
    # linux
    sed -i "s/${kvs[0]}/${kvs[1]}/g" docker-compose.yml
    # osx
    sed -i '' "s/${kvs[0]}/${kvs[1]}/g" docker-compose.yml
done

 

:

[Elasticsearch] LowLevelRestClient 를 이용한 개발 시 Json 결과 처리

Elastic/Elasticsearch 2021. 11. 25. 14:08

보통 Elasticsearch LLRC 를 이용해서 RESTful API 요청 하게 되면
...중략...
Request request = new Request(...중략...);
Response response = esClient.getRestClient().performRequest(request);
String body = EntityUtils.toString(response.getEntity());
...중략...

String 으로 결과를 받아서 리턴 하게 되는데 이 과정에서 JSON String 변환 시 slash 가 추가 되는 불편함이 있을 수 있습니다.
이걸 해소 하려면
...중략...
String body = EntityUtils.toString(response.getEntity());
JsonNode jsonNode = ObjectMapper.readTree(body);
...중략...
readTree 해서 JsonNode Object 로 변환 한 후 처리 하시면 {}, [] 등 모두 깔끔하게 처리가 가능 합니다.

 

ASIS)

{
	"response": "{ \"alias\": \"henry\" }"
}

{
	"response": "[
    	{ \"alias1\": \"henry\" },
        { \"alias2\": \"jeong\" }
      ]"
}

 

TOBE)

{
	"response": { "alias": "henry" }
}

{
	"response": [
    	{ "alias1": "henry" },
        { "alias2": "jeong" }
      ]
}

 

:

[Bash] 문자열 비교 예제

ITWeb/개발일반 2021. 7. 27. 08:11
#!/bin/bash

retry='retry'

if [ $retry = "retry" ]; then
  echo 'true - 1'
fi

if [[ $retry = "retry" ]]; then
  echo 'true - 2'
fi

if [[ "$retry" = "retry" ]]; then
  echo 'true - 3'
fi

세 예제 다 true 리턴 합니다.

:

[Bash] Bash function, array parameters, str replace 등

ITWeb/개발일반 2020. 4. 20. 11:18

bash script 에서 function 사용은 호출 위치 보다 위에 function 선언이 되어 있어야 합니다.

#!/usr/bin/env bash

function 함수명() {
...
}

## 예제

#!/usr/bin/env bash

function helloWorld() {
  echo 'Hello World!!'
}

helloWorld

 

function  에 다중 array paramters 를 넘기는 예제는 아래와 같습니다.

#!/usr/bin/env bash

function deployElasticStack() {
  local instances=($1)
  local targets=($2)

  for instance in ${instances[@]}
  do

    local hostIpUser=($(echo $instance | tr ":" "\n"))

    for target in ${targets[@]}
    do
...중략...
    done
  done
}

selfHost=$(hostname -I|cut -f1 -d ' ')

instanceArr=("xxx.xxx.xxx.xxx:ubuntu" "xxx.xxx.xxx.xxx:ec2-user" "xxx.xxx.xxx.xxx:ubuntu")
metricbeatArr=("xxx.xxx.xxx.xxx" "xxx.xxx.xxx.xxx" "xxx.xxx.xxx.xxx")

deployElasticStack "${instanceArr[*]}" "${metricbeatArr[*]}" "$selfHost" "metricbeat"

 

해당 장비의 IP 정보를 가져 오는 예제는 아래와 같습니다.

$ hostname -I

$ hostname -I|cut -f1 -d ' '

$ ip route get 8.8.8.8 | sed -n '/src/{s/.*src *\([^ ]*\).*/\1/p;q}'

 

file 내 특정 문자열을 치환 하는 예제는 아래와 같습니다.

$ sed -i "s/소스문자열/치환문자열/g" configuration.yml

# osx 에서는 아래와 같이 합니다.
$ sed -i "" "s/소스문자열/치환문자열/g" configuration.yml

 

:

[Java] String split 성능테스트.

ITWeb/개발일반 2014. 2. 13. 16:30

아래 코드에 오류가 있습니다.

뭐 수정은 안할 예정이구요. ㅋㅋ 알아서 하세요.

딱 보면 논리적으로 틀린 부분이 보입니다.

힌트, 첨 부터 구분할 대상이 없다면.........ㅋ

=============================================================================


뭐 성능 테스트라고 하기까지는 그렇고 String.split 이 성능이 나쁘다는 사실은 잘 알고 있을 거라고 생각 합니다.

그래서 가능 하면 이넘을 안쓰려고 하는데요.

기본적으로 비교 되는 것들이 scanner vs split vs tokenizer 인데요.

이건 이미 비교 자료가 많으니 일단 pass ~


오늘 제가 그냥 테스트한건 split vs indexOf 형변환 vs indexOf 입니다.

편의상 이름을 아래 처럼 하겠습니다.

String.split vs split vs tokenizer


[테스트 코드]


    @Test
    public void testSplit() {
        String original = "field1,field2,field3,field4,field5,field6,field7,field8,field9,field10";
        String[] tokens;
        List tokenList;
       
        long startTime = 0;
        int elapsedTime = 0;
        long loop = 10000000;
       
        startTime = System.currentTimeMillis();
        for ( int i=0; i<loop; i++ ) {
            tokens = original.split(",");
        }
        elapsedTime = (int)(System.currentTimeMillis() - startTime);
        log.debug("String.split EXECUTE:"+elapsedTime);
       
        startTime = System.currentTimeMillis();
        for ( int i=0; i<loop; i++ ) {
            tokens = split(original, ",");
        }
        elapsedTime = (int)(System.currentTimeMillis() - startTime);
        log.debug("split EXECUTE:"+elapsedTime);
       
        startTime = System.currentTimeMillis();
        for ( int i=0; i<loop; i++ ) {
            tokenList = tokenizer(original, ",");
        }
        elapsedTime = (int)(System.currentTimeMillis() - startTime);
        log.debug("tokenizer EXECUTE:"+elapsedTime);
       
    }


[결과]

DEBUG: String.split EXECUTE:7935
DEBUG: split EXECUTE:3253
DEBUG: tokenizer EXECUTE:2896


아래는 테스트로 작성한 split, tokenizer 함수 입니다.

이 함수에 대한 최적화는 pass (그냥 기능만 되는 걸로.. )


    public String[] split(String original, String delimeter) {
        ArrayList<String> tokens = new ArrayList<String>();
        tokens = (ArrayList<String>)tokenizer(original, delimeter);
       
        String[] rets = new String[tokens.size()];
        rets = tokens.toArray(rets);
       
        return rets;
    }
   
    public List tokenizer(String original, String delimeter) {
        ArrayList<String> tokens = new ArrayList<String>();
        String token = "";
        int beginIdx = 0;
        int endIdx = original.indexOf(delimeter);
       
        while ( endIdx > -1 ) {
            token = original.substring(beginIdx, endIdx);
            tokens.add(token);
            beginIdx = endIdx + 1;
            original = original.substring(beginIdx);
            beginIdx = 0;
            endIdx = original.indexOf(delimeter);
           
            if ( endIdx == -1 ) {
                if ( !original.isEmpty() ) {
                    tokens.add(original);
                }
            }
        }
       
        return tokens;
    }


:

c++ string replace

ITWeb/개발일반 2013. 2. 1. 13:08

[Reference URL]
http://www.cplusplus.com


The below code is valid on my machine.

str_vector_t sReplVector;

str_vector_const_iterator_t sIterator;

std::string findStr = "";

int32_t pos = 0;


for ( sIterator = sQueryVector1.begin(); sIterator != sQueryVector1.end(); sIterator++ ) {

    findStr = sIterator->c_str();

    pos = findStr.find("INSERT INTO Tbl1");

    LOGDEBUG("[ASIS][sQueryVector1][%s]", sIterator->c_str());


    if ( pos > 0 ) {

        findStr.replace(pos, 17, "INSERT INTO Tbl2");

        sReplVector.push_back(findStr);

        LOGDEBUG("[TOBE][sQueryVector1][%s]", findStr.c_str());

    }

}


General example by cpluscplus.com
http://www.cplusplus.com/reference/string/string/replace/

// replacing in a string

#include <iostream>
#include <string>

int main ()
{
  std::string base="this is a test string.";
  std::string str2="n example";
  std::string str3="sample phrase";
  std::string str4="useful.";

  // replace signatures used in the same order as described above:

  // Using positions:                 0123456789*123456789*12345
  std::string str=base;           // "this is a test string."
  str.replace(9,5,str2);          // "this is an example string." (1)
  str.replace(19,6,str3,7,6);     // "this is an example phrase." (2)
  str.replace(8,10,"just a");     // "this is just a phrase."     (3)
  str.replace(8,6,"a shorty",7);  // "this is a short phrase."    (4)
  str.replace(22,1,3,'!');        // "this is a short phrase!!!"  (5)

  // Using iterators:                                               0123456789*123456789*
  str.replace(str.begin(),str.end()-3,str3);                    // "sample phrase!!!"      (1)
  str.replace(str.begin(),str.begin()+6,"replace");             // "replace phrase!!!"     (3)
  str.replace(str.begin()+8,str.begin()+14,"is coolness",7);    // "replace is cool!!!"    (4)
  str.replace(str.begin()+12,str.end()-4,4,'o');                // "replace is cooool!!!"  (5)
  str.replace(str.begin()+11,str.end(),str4.begin(),str4.end());// "replace is useful."    (6)
  std::cout << str << '\n';
  return 0;
}


: