How to extract the first two characters of a string in shell scripting?

前端 未结 14 2049
-上瘾入骨i
-上瘾入骨i 2020-12-07 13:54

For example, given:

USCAGoleta9311734.5021-120.1287855805

I want to extract just:

US
相关标签:
14条回答
  • 2020-12-07 14:24

    Just for the sake of fun Ill add a few that, although they are over complicated and useless, they were not mentioned :

    head -c 2 <( echo 'USCAGoleta9311734.5021-120.1287855805')
    
    echo 'USCAGoleta9311734.5021-120.1287855805' | dd bs=2 count=1 status=none
    
    sed -e 's/^\(.\{2\}\).*/\1/;' <( echo 'USCAGoleta9311734.5021-120.1287855805')
    
    cut -c 1-2 <( echo 'USCAGoleta9311734.5021-120.1287855805')
    
    python -c "print(r'USCAGoleta9311734.5021-120.1287855805'[0:2])"
    
    ruby -e 'puts "USCAGoleta9311734.5021-120.1287855805"[0..1]'
    
    0 讨论(0)
  • 2020-12-07 14:27

    If you're in bash, you can say:

    bash-3.2$ var=abcd
    bash-3.2$ echo ${var:0:2}
    ab
    

    This may be just what you need…

    0 讨论(0)
提交回复
热议问题