파일의 레코드에서 문자열 선택

파일의 레코드에서 문자열 선택

기록이 포함된 파일이 있습니다. 기록 형식은 다음과 같습니다.

Record: XXXXXX [
{variable number of lines and content}
]

기록의 어느 시점에서 다음이 있을 수 있습니다.

Start to do this thing

"start"라는 단어와 일치하는 레코드 번호와 레코드의 행을 추출하고 싶습니다.

현재 내가 사용하고 있는

egrep "Record|Start" inputfile.txt >> outputfile.txt

Record하지만 일치하지 않는 일치하는 행을 수동으로 삭제해야 합니다 Start. 이상적으로는 이 단계가 완료되기를 바랍니다. 어떤 제안이라도 감사하겠습니다.

답변1

해결책:

샘플 input.txt파일:

Record: 111111 [
text
test
Start to do this thing
text
]
Record: 222222 [
{variable number of lines and content}
]
Record: 333333 [
text
text
text
Start to do another thing
text
]

일하다:

awk '/^Record: .*\[$/{ f=1; n=$2 }/^\]/{f=0}f && /^Start/{ print n, $0 }' input.txt

산출:

111111 Start to do this thing
333333 Start to do another thing

답변2

예제 파일을 사용하여 수정 사항을 적용하여 연속으로 세 번 반복합니다.

Record: XXXXXX [
{variable number of lines and content}
Start to do this thing
]
Record: YYYYYY [
{variable number of lines and content}
Stop doing this thing
]
Record: ZZZZZZ [
{variable number of lines and content}
Start again
]

그 다음에:

$ awk '/^Record:/ { r = $2 } /^Start/ { print r ":", $0 }' file
XXXXXX: Start to do this thing
ZZZZZZ: Start again

로 시작하는 줄이 보이면 레코드 번호/레이블을 선택하여 Record:변수에 저장하면 됩니다 r. 그런 다음 로 시작하는 줄을 찾으면 Start찾은 레코드 레이블과 해당 줄을 인쇄합니다.

라인이 안되면시작의 경우 단어와 줄 시작 사이에 공백을 허용 하도록 Start정규식을 변경해야 할 수도 있습니다 ./^Start//^ *Start/

다음이 있으면 실패합니다.다른파일의 트랜잭션 간에 일치하는 레코드가 기록됩니다 Start.

관련 정보