195. Tenth Line
Description
Given a text file file.txt
, print just the 10th line of the file.
Example:
Assume that file.txt has the following content:
Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 Line 10
Your script should output the tenth line, which is:
Line 10
Note:
- If the file contains less than 10 lines, what should you output?
- There’s at least three different solutions. Try to explore all possibilities.
Submitted Code
# Read from the file file.txt and output the tenth line to stdout.
# Solution 1
awk 'NR==10' file.txt
# Solution 2
sed -n '10p' ./file.txt
# Solution 3
tail -n+10 file.txt | head -1
- awk
- 텍스트 파일을 줄 단위로 처리하는 명령어
NR
은 현재 읽고 있는 줄 번호이기 때문에 NR이 10일 때 해당 줄 출력
- sed
- 파일을 읽으며 특정 패턴을 수정하거나 출력하는 데 사용되는 명령어
-n
옵션으로 명시적으로 지정한 출력만 보이기10p
로 10번째 줄 출력
- tail | head
- tail
-n+10
로 10번째 줄부터 파일 끝까지 출력 - head
-1
로 tail로 출력된 내용 중 1번째 줄만 출력 - 두 개의 명령어를 파이프로 연결하여 사용
- tail
Other Solutions
1st
cnt=0 # 줄 번호를 세는 변수
while read line && [ $cnt -le 10 ]; do # 읽을 줄이 있으면 line에 저장 후 조건문(cnt가 10 이하일 때만 루프 반복) 실행
let 'cnt = cnt + 1' # 줄 번호를 1씩 증가시키는 산술 연산 수행
if [ $cnt -eq 10 ]; then # 현재 줄 번호가 10인지 확인
echo $line # 10번째 줄이면 출력
exit 0 # 출력 후 프로그램 종료
fi
done < file.txt