
두 번째 줄 이전의 모든 내용을 인쇄하고 싶습니다.시작with * i
(별표, 공백, 소문자 I)는 이 줄과 이 줄을 포함하여 그 뒤의 모든 항목을 각각 제외합니다.
예를 들어 다음과 같은 텍스트 파일이 있다고 가정해 보겠습니다.
* misc: go to the park
with your dog
* important: sell badges
the bigger the pricier
24 left right now
* important: go to the mall
get clothes
* important: finish homework
먼저 이것을 인쇄하고 싶습니다.
* misc: go to the park
with your dog
* important: sell badges
the bigger the pricier
24 left right now
그런 다음 이:
* important: go to the mall
get clothes
* important: finish homework
sed를 사용하여 이 작업을 어떻게 수행할 수 있나요?
나는 노력했다
sed '/\* [^i]/,$ { /\* [^i]/,$ d}' /path/to/txt/
하지만 이전의 모든 내용을 인쇄합니다.처음일치하는 라인.
각 부분을 추출하기 위해 두 개의 별도 스크립트가 필요합니다.
답변1
내가 제안 할게awk
처리(나는 이것이 더 유연하고 강력할 것이라고 믿는다):
awk '/^\* i/ && ++c == 2{ print r ORS; r=""; c=0 }
{ r=(r? r ORS:"")$0 }
END{ print r }' file
산출:
* misc: go to the park
with your dog
* important: sell badges
the bigger the pricier
24 left right now
* important: go to the mall
get clothes
* important: finish homework
현재의 간단한 사례(추가 논리 없음)의 경우 다음과 같이 단축할 수 있습니다.
awk '/^\* i/ && ++c == 2{ print "" }1' file
필요한 부분을 개별적으로 추출하려면 여전히 단일 명령을 사용 하지만 조건부 값 (첫 번째 부분, 이전 부분) 또는 (두 번째 부분, 다음 부분)을 허용하는 awk
동적 매개변수를 사용합니다 .part
1
2
계획:
awk -v part=[12] '/^\* i/ && ++c == 2{ if (part == 1) exit; else f=1 } part == 1 || (part == 2 && f)' FILE
용법:
- 인쇄"앞으로"부분:
$ awk -v part=1 '/^\* i/ && ++c==2{ if (part==1) exit; else f=1 }
> part==1 || (part==2 && f)' file
* misc: go to the park
with your dog
* important: sell badges
the bigger the pricier
24 left right now
- 인쇄"뒤쪽에"부분:
$ awk -v part=2 '/^\* i/ && ++c==2{ if (part==1) exit; else f=1 }
> part==1 || (part==2 && f)' file
* important: go to the mall
get clothes
* important: finish homework
답변2
awk보다 더 복잡한 sed를 사용할 수도 있습니다.
cat sedscript.sh
deb=$1
sed 's/.*/'"$deb"'\n&/
:A
/^1/{
N
/\n\* i/!bA
:B
N
/\n\* i[^\n]*$/!bB
s/\n[^\n]*$//
s/[^\n]*\n//
q
}
:C
/^2/{
N
/\n\* i/!bC
:D
N
/\n\* i[^\n]*$/!bD
s/.*\n//
:E
N
bE
q
}
d
' $2
다음과 같이 호출하세요.
첫 번째 부분에 대해서는
./sedscript.sh 1개 파일
두 번째 부분을 위해
./sedscript.sh 2 입력 파일