수색…


텍스트 파일에서 특정 줄 추출

파일이 있다고 가정 해 봅시다.

cat -n lorem_ipsum.txt
 1    Lorem Ipsum is simply dummy text of the printing and typesetting industry.
 2    Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
 3    It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
 4    It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

이 파일에서 2 번과 3 번 줄을 추출하려고합니다.

awk 'NR==2,NR==3' lorem_ipsum.txt

그러면 2 행과 3 행이 인쇄됩니다.

 2    Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
 3    It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.

특정 라인에서 특정 컬럼 / 필드 추출

다음 데이터 파일이있는 경우

cat data.csv
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50

어쩌면 당신은 세 번째 줄의 네 번째 열을 읽을 필요가 있습니다. 이것은 "24"가 될 것입니다.

awk 'NR==3 { print $4 }' data.csv

주는

24

on-the-fly 행 수정 (예 : Windows 줄 끝 수정)

파일에 Windows 또는 Unix와 유사한 줄 끝 (또는 두 개가 혼합되어있을 수도 있음)이 포함되어 있으면 의도 한 텍스트 바꾸기가 예상대로 작동하지 않을 수 있습니다.

견본:

$ echo -e 'Entry 1\nEntry 2.1\tEntry 2.2\r\nEntry 3\r\n\r\n' \
> | awk -F'\t' '$1 != "" { print $1 }' \
> | hexdump -c
0000000   E   n   t   r   y       1  \n   E   n   t   r   y       2   .
0000010   1  \n   E   n   t   r   y       3  \r  \n  \r  \n            
000001d

이것은 awk 스크립트의 시작 부분에 삽입되는 추가 규칙에 의해 쉽게 고칠 수 있습니다 :

/\r$/ { $0 = substr($0, 1, length($0) - 1) }

액션은 next 끝나지 않으므로 이전과 마찬가지로 다음 규칙이 적용됩니다.

샘플 (줄 끝이 수정 됨) :

$ echo -e 'Entry 1\nEntry 2.1\tEntry 2.2\r\nEntry 3\r\n\r\n' \
> | awk -F'\t' '/\r$/ { $0 = substr($0, 1, length($0) - 1) } $1 != "" { print $1 }' \
> | hexdump -c
0000000   E   n   t   r   y       1  \n   E   n   t   r   y       2   .
0000010   1  \n   E   n   t   r   y       3  \n                        
000001a


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow