
텍스트 파일이 있습니다. 작업 - 파일에서 첫 번째 줄과 마지막 줄 가져오기
$ cat file | grep -E "1|2|3|4" | commandtoprint
$ cat file
1
2
3
4
5
cat 출력 없이 필요합니다(1과 5만).
~$ cat file | tee >(head -n 1) >(wc -l)
1
2
3
4
5
5
1
어쩌면 awk와 더 짧은 솔루션이 존재할 수도 있습니다 ...
답변1
sed해결책:
sed -e 1b -e '$!d' file
if 에서 읽을 때 stdin
다음과 같습니다(예 ps -ef
: ).
ps -ef | sed -e 1b -e '$!d'
UID PID PPID C STIME TTY TIME CMD
root 1931 1837 0 20:05 pts/0 00:00:00 sed -e 1b -e $!d
머리 & 꼬리해결책:
(head -n1 && tail -n1) <file
데이터가 명령( ps -ef
)에서 나오는 경우:
ps -ef 2>&1 | (head -n1 && tail -n1)
UID PID PPID C STIME TTY TIME CMD
root 2068 1837 0 20:13 pts/0 00:00:00 -bash
앗해결책:
awk 'NR==1; END{print}' file
또한 다음과 같은 파이프 예제도 있습니다 ps -ef
.
ps -ef | awk 'NR==1; END{print}'
UID PID PPID C STIME TTY TIME CMD
root 1935 1837 0 20:07 pts/0 00:00:00 awk NR==1; END{print}
답변2
sed -n '1p;$p' file.txt
file.txt 의 첫 번째 줄과 마지막 줄을 인쇄합니다.
답변3
재미있고 순수한 Bash≥4 방식:
cb() { (($1-1>0)) && unset "ary[$1-1]"; }
mapfile -t -C cb -c 1 ary < file
ary
그런 다음 첫 번째 필드(예: index 0
)가 의 첫 번째 줄이고 file
마지막 필드가 의 마지막 줄인 배열을 갖게 됩니다 file
. 콜백 cb
(배열의 모든 줄을 후루룩 마시고 싶은 경우 선택 사항)은 메모리를 복잡하게 만들지 않도록 모든 중간 줄의 설정을 해제합니다. 무료 부산물로 파일의 줄 수(배열의 마지막 인덱스 + 1)도 갖게 됩니다.
데모:
$ mapfile -t -C cb -c 1 ary < <(printf '%s\n' {a..z})
$ declare -p ary
declare -a ary='([0]="a" [25]="z")'
$ # With only one line
$ mapfile -t -C cb -c 1 ary < <(printf '%s\n' "only one line")
$ declare -p ary
declare -a ary='([0]="only one line")'
$ # With an empty file
$ mapfile -t -C cb -c 1 ary < <(:)
declare -a ary='()'
답변4
고양이가 없으면:
$ cat file |tee >(head -n1) >(tail -n1) >/dev/null
1
5
또는
$ (head -n1 file;tail -n1 file)
1
5