
awk
"start"에 대한 입력 파일을 검색하고 "next"가 포함된 줄을 찾아 다음 줄을 표시하는 스크립트를 어떻게 작성할 수 있습니까 ? 이 같은:
[user]$ cat test.txt
start
next
This line should print
Ignore this
[user]$ display.awk test.txt
This line should print
[user]$ cat test1.txt
Ignore this
next
Ignore this
start
Ignore this
next
This line should print
Ignore this
next
Too late so ignore this too
start
Ignore this too
[user]$ display.awk test1.txt
This line should print
답변1
이것은 문장입니다:
awk 'BEGIN {start="no"; nextline="no"}; nextline=="yes" {print; exit}; (start=="yes" && /^next$/) {nextline="yes"}; /^start$/ {start="yes"}' test.txt
독립형 스크립트로:
#!/bin/awk -f
BEGIN {start="no"; nextline="no"}
nextline=="yes" {print; exit}
(start=="yes" && /^next$/) {nextline="yes"}
/^start$/ {start="yes"}
설명하다
첫 번째 지점을 먼저 읽은 다음 나머지 지점을 반대로 읽는 것이 더 합리적일 수 있습니다.
BEGIN {start="no"; nextline="no"}
: 먼저 두 변수를 다음으로 설정합니다"no"
(즉, 아직 찾지 못했습니다). NB는next
예약어이므로 사용했습니다nextline
.nextline=="yes" {print; exit}
next
: 이전 줄에서 찾으면 해당 줄을 인쇄하고 종료합니다.(start=="yes" && /^next$/) {nextline="yes"}
: 발견 후 행에서도 찾으면 다음으로 설정start
됩니다 .next
nextline
"yes"
/^start$/ {start="yes"}
: 시작을 찾으면start
으로 설정합니다"yes"
.
답변2
대체 솔루션 sed
:
sed -n '/start/,${ # in this range
$!{ # if not the last line
/next/{ # and if line matches "next"
n # read in the next line
p # print pattern space
q # quit
}
}
}' infile
그리고 gnu sed
:
sed -n '/start/,${$!{/next/{n;p;q}}}' infile
답변3
이것도 작동해야합니다
awk 'BEGIN {l1=0} /^start$/{l1=1} /^next$/ && l1==1 {l2=NR+1} NR==l2 {print;l1=0}' test.txt
이는 레코드 번호 NR을 사용하여 출발선 이후에 처음 만난 레코드 이후의 레코드를 인쇄합니다.