
我有文字檔。任務 - 從文件中取得第一行和最後一行
$ 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解決方案:
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
,其中第一個字段(即索引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