Bash에서 문자열의 마지막 x자 액세스
제가 그걸 알게 된 건${string:0:3}
문자열의 처음 3글자에 액세스할 수 있습니다.마지막 세 글자에 동일하게 쉽게 접근할 수 있는 방법이 있나요?
의 마지막 세 글자string
:
${string: -3}
또는
${string:(-3)}
(사이의 간격에 주의해 주세요):
그리고.-3
첫 번째 형식으로)
${parameter:offset}
${parameter:offset:length}
Expands to up to length characters of parameter starting at the character
specified by offset. If length is omitted, expands to the substring of parameter
starting at the character specified by offset. length and offset are arithmetic
expressions (see Shell Arithmetic). This is referred to as Substring Expansion.
If offset evaluates to a number less than zero, the value is used as an offset
from the end of the value of parameter. If length evaluates to a number less than
zero, and parameter is not ‘@’ and not an indexed or associative array, it is
interpreted as an offset from the end of the value of parameter rather than a
number of characters, and the expansion is the characters between the two
offsets. If parameter is ‘@’, the result is length positional parameters
beginning at offset. If parameter is an indexed array name subscripted by ‘@’ or
‘*’, the result is the length members of the array beginning with
${parameter[offset]}. A negative offset is taken relative to one greater than the
maximum index of the specified array. Substring expansion applied to an
associative array produces undefined results.
Note that a negative offset must be separated from the colon by at least one
space to avoid being confused with the ‘:-’ expansion. Substring indexing is
zero-based unless the positional parameters are used, in which case the indexing
starts at 1 by default. If offset is 0, and the positional parameters are used,
$@ is prefixed to the list.
이 답변에는 몇 가지 규칙적인 뷰가 있기 때문에 John Rix의 코멘트에 대응할 수 있는 가능성이 추가되어 있습니다.John Rix가 언급했듯이 문자열의 길이가 3보다 작으면${string: -3}
빈 문자열로 확장됩니다.이 경우, 이 경우,string
, 다음을 사용할 수 있습니다.
${string:${#string}<3?0:-3}
이 명령어는?:
3진수 if 연산자, 셸 산술에서 사용할 수 있습니다.설명된 바와 같이 오프셋은 산술식이기 때문에 이는 유효합니다.
POSIX 준거 솔루션 업데이트
앞부분은 Bash를 사용할 때 가장 좋은 옵션을 제공합니다.POSIX 쉘을 타깃으로 하는 경우 다음과 같은 옵션(파이프나 외부 도구를 사용하지 않음)이 있습니다.cut
):
# New variable with 3 last characters removed
prefix=${string%???}
# The new string is obtained by removing the prefix a from string
newstring=${string#"$prefix"}
여기서 주목해야 할 주요 사항 중 하나는 에 대한 견적을 사용하는 것입니다.prefix
매개 변수 확장 내부.이것은, POSIX 레퍼런스(섹션의 말미)에 기재되어 있습니다.
서브스트링 가공에는 다음 4가지 파라미터 확장기능이 있습니다.각각의 경우 패턴을 평가하기 위해 정규 표현 표기법 대신 패턴 매칭 표기법(패턴 매칭 표기법 참조)을 사용해야 한다.매개 변수가 '#', '*' 또는 '@'이면 확장 결과가 지정되지 않습니다.파라미터가 설정되지 않고 set -u가 유효할 경우 확장은 실패합니다.전체 매개변수 확장 문자열을 이중 따옴표로 묶으면 다음과 같은 4가지 패턴 문자가 인용되지 않아야 하며, 가새 안에 있는 따옴표는 이 효과를 발휘해야 합니다.각 품종에서 단어가 생략된 경우 빈 패턴을 사용해야 한다.
이것은 문자열에 특수 문자가 포함되어 있는 경우 중요합니다.예: (대시),
$ string="hello*ext"
$ prefix=${string%???}
$ # Without quotes (WRONG)
$ echo "${string#$prefix}"
*ext
$ # With quotes (CORRECT)
$ echo "${string#"$prefix"}"
ext
물론, 이것은 문자 수를 미리 알고 있어야만 사용할 수 있습니다. 왜냐하면 당신은 숫자를 하드코드해야 하기 때문입니다.?
파라미터의 확장에 대해서는 설명하지만, 그럴 때는 휴대성이 뛰어난 솔루션입니다.
하시면 됩니다.tail
:
$ foo="1234567890"
$ echo -n $foo | tail -c 3
890
마지막 세 글자를 얻기 위한 다소 우회적인 방법은 다음과 같습니다.
echo $foo | rev | cut -c1-3 | rev
하나의 은 ' 낫다'를 하는 것입니다.grep -o
작은 정규식 마법으로 세 글자를 얻고 줄 끝:
$ foo=1234567890
$ echo $foo | grep -o ...$
890
, 는, 「1 ~ 3」을 사용합니다.egrep
하여: "regex를 실행합니다.
$ echo a | egrep -o '.{1,3}$'
a
$ echo ab | egrep -o '.{1,3}$'
ab
$ echo abc | egrep -o '.{1,3}$'
abc
$ echo abcd | egrep -o '.{1,3}$'
bcd
'하다, 하다, 하다, 하다'와를 사용할 수도 있습니다.5,10
5번 10번 10번으로 나누다
1. 일반 서브스트링
gniourf_gniourf의 질문과 답변을 일반화하기 위해 예를 들어, 끝에서 7번째에서 3번째까지의 문자를 잘라내는 경우 다음 구문을 사용할 수 있습니다.
${string: -7:4}
여기서 4는 코스 길이(7-3)입니다.
2. 2. 체체사 2 2 2cut
이지만, 는 단지 gniourf_gniourf를 사용하여 대체 을 추가하고 .cut
:
echo $string | cut -c $((${#string}-2))-
서서,,${#string}
는 문자열의 길이입니다.후행 "-"는 끝까지 절단된 것을 의미합니다.
3. 3. 체체사 3 3awk
에서는 대신 합니다.awk
의 substr(string, start, length)
길이를 생략하면 끝까지 갑니다. length($string)-2)
이치
echo $string | awk '{print substr($1,length($1)-2) }'
언급URL : https://stackoverflow.com/questions/19858600/accessing-last-x-characters-of-a-string-in-bash
'it-source' 카테고리의 다른 글
탭을 클릭하면 셸 초기화 문제가 발생합니다.getcwd의 문제점은 무엇입니까? (0) | 2023.04.16 |
---|---|
브라우저별로 URL의 최대 길이는 몇 개입니까? (0) | 2023.04.16 |
XLRD 패키지를 사용한 Excel 시트 셀 색상 코드 식별 (0) | 2023.04.16 |
CSS를 사용하여 텍스트를 세로 방향으로 중앙에 배치하려면 어떻게 해야 합니까? (0) | 2023.04.16 |
Bash 디렉토리가 아닌 파일만 나열하는 방법 (0) | 2023.04.11 |