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

前端 未结 14 2048
-上瘾入骨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:03
    perl -ple 's/^(..).*/$1/'
    
    0 讨论(0)
  • 2020-12-07 14:06

    You've gotten several good answers and I'd go with the Bash builtin myself, but since you asked about sed and awk and (almost) no one else offered solutions based on them, I offer you these:

    echo "USCAGoleta9311734.5021-120.1287855805" | awk '{print substr($0,0,2)}'
    

    and

    echo "USCAGoleta9311734.5021-120.1287855805" | sed 's/\(^..\).*/\1/'
    

    The awk one ought to be fairly obvious, but here's an explanation of the sed one:

    • substitute "s/"
    • the group "()" of two of any characters ".." starting at the beginning of the line "^" and followed by any character "." repeated zero or more times "*" (the backslashes are needed to escape some of the special characters)
    • by "/" the contents of the first (and only, in this case) group (here the backslash is a special escape referring to a matching sub-expression)
    • done "/"
    0 讨论(0)
  • 2020-12-07 14:07

    easiest way is

    ${string:position:length}
    

    Where this extracts $length substring from $string at $position.

    This is a bash builtin so awk or sed is not required.

    0 讨论(0)
  • 2020-12-07 14:07

    Is this what your after?

    my $string = 'USCAGoleta9311734.5021-120.1287855805';
    
    my $first_two_chars = substr $string, 0, 2;
    

    ref: substr

    0 讨论(0)
  • 2020-12-07 14:09

    If your system is using a different shell (not bash), but your system has bash, then you can still use the inherent string manipulation of bash by invoking bash with a variable:

    strEcho='echo ${str:0:2}' # '${str:2}' if you want to skip the first two characters and keep the rest
    bash -c "str=\"$strFull\";$strEcho;"
    
    0 讨论(0)
  • 2020-12-07 14:14

    Just grep:

    echo 'abcdef' | grep -Po "^.."        # ab
    
    0 讨论(0)
提交回复
热议问题