tr : 문자열 split, 변환, awk+tr을 사용한 floating 연산, sort, uniq, cut

markyang92·2021년 7월 26일
0

linux (ubuntu/debian)

목록 보기
30/37
post-thumbnail

tr

  • 문자열 변환/삭제
$ tr [option] str1 [str2]  1 #!/bin/bash

option:
  -d	str1에서 지정한 문자를 삭제하여 stdout으로 출력
  -s	str1에서 지정한 문자를 str2로 치환하여 stdout으로 출력
  -t	str1을 str2의 길이로 자른다.
  
str에 Regex 사용 가능

소문자 -> 대문자

$ cat <FILE> | tr 'a-z' 'A-Z'

소문자 <-> 대문자

$ cat <FILE> | tr 'a-zA-Z' 'A-Za-z'

-d : 제거 문자

$ cat <FILE> | tr -d '0-9'

치환

  • 숫자 -> * 문자로 치환
$ cat <FILE> | tr -s '0-9' '*'

예제

'/' split해 배열로

# VAR=/home/user/workspace/hello/world

$ echo $VAR | tr -s '/' ' '
 home user workspace hello world
#!/bin/bash

VAR="/home/user/workspace/hello/world"
declare -a arr
VAR=$(echo $VAR | tr -s '/' ' ')

for now in $VAR; do
    arr+=(${now})
done

for now in ${arr[@]}; do
    echo $now
done

# === 출력 === #
home
user
workspace
hello
world

floating 연산

  1. Byte -> {K,M,G,T}Byte
#!/bin/bash

Byte=290121512

function byteToHumanreadable () {
    for ((i=0;i<=4;i++)); do
        Byte=$(echo "${Byte}" | awk '{if($1<1024) printf("%.2f,done\n",$1); else printf("%f\n",$1/1024)}')
        if [[ ${Byte} =~ "done" ]]; then
            case $i in
                0) SUFFIX="B" ;;
                1) SUFFIX="KB" ;;
                2) SUFFIX="MB" ;;
                3) SUFFIX="GB" ;;
                4) SUFFIX="TB" ;;
            esac
            echo ${Byte} | tr -s ",done" "${SUFFIX}"
            break
        fi
    done
}


byteToHumanreadable
===== 출력 =====
276.68MB

sort

  • sort는 텍스트로된 파일의 '행'단위 정렬
    • 기본으로 '오름차순'
    • 각 행의 첫 번째 단어를 알파벳 오름차순으로 정렬한다.
      • 첫 번째 단어가 동일할 경우 두번째 문자를 비교한다.
$ sort [opt] <file>

opt:
  -r : 내림차순 정렬
  -k 2 : 2번째 필드를 기준으로 정렬
  -u : 중복된 내용을 하나로 취급하여 정렬
  -z : 0 <NULL>을 line terminator

uniq


cut

cut -d 구분자 -f필드번호

cut -d ' ' -f5

profile
pllpokko@alumni.kaist.ac.kr

0개의 댓글