
긴 문자열이 있고 처음 나타나는 하위 문자열을 찾고 싶지만 하위 문자열에 큰따옴표가 포함되어 있습니다. 내가 아는 유일한 방법은 다음과 같습니다.
mystr='a very, very, extremely, incredibly long string of text that contains the phrase he said, "Hello!" somewhere in the middle'
strpos=`expr index "$mystr" Hello`
echo $strpos
92를 반환합니다. 하지만 하위 문자열에 큰따옴표가 포함되어 있으면 작동하지 않습니다.
strpos=`expr index "$mystr" he said, "Hello`
큰따옴표(및 공백)를 이스케이프 처리해 보았습니다. 문자열을 작은따옴표로 묶어서 찾으려고 했습니다. "예기치 않은 EOF" 또는 "구문 오류"를 수신하지 않고 실행하면 "2"와 같은 터무니없는 결과가 반환됩니다. (이 직위는 수천개가 있습니다.) 제가 원하는 것을 할 수 없을 것 같지만 expr index
그렇지 않다면 어떻게 될까요?할 수 있는내가 합니까?
답변1
제 생각엔 첫 번째 문자열에서 두 번째 문자열의 문자를 검색하는 것 같아요. 그렙을 사용할 수 있습니다
mystr='a very, very, extremely, incredibly long string of text that contains 2 the phrase he said, "Hello!" somewhere in the middle'
echo "$mystr"| grep -o -b Hello!
그것은 돌아올 것이다 91:Hello!
. 여기서 인덱스는 0부터 시작합니다.
같은 상황이 여러 번 발생하면 출력은 다음과 같습니다.
0:a 58:a 65:a 77:a 85:a
큰따옴표도 검색하려면 이스케이프 처리하세요.
echo "$mystr"| grep -o -b \"Hello!\"
출력은 다음과 같습니다
90:"Hello!"
답변2
매개변수 확장만 사용하십시오.
mystr='a very, very, extremely, incredibly long string of text that contains the phrase he said, "Hello!" somewhere in the middle'
searchstr='"Hello!"'
newstr="${mystr%%$searchstr*}"
echo "position = $((${#newstr} + 1))"
답변3
이것이 당신이 찾고 있는 것인지 확인해 봅시다:
mystr='a very, very, extremely, incredibly long string of text that contains the phrase he said, "Hello!" somewhere in the middle'
$ var=$(echo "$mystr" | grep -o -b "Hello!" | head -1)
$ echo "$var"
91:Hello!
$ pos="${var%:*}"
$ echo "$pos"
91