を使用してファイルの最初の行を読み取るにはどうすればよいcat
ですか?
11 に答える
必要ありませんcat
。
head -1 file
正常に動作します。
head
代わりに使用してください。
head -n 1 file.txt
さまざまな方法があります。
sed -n 1p file
head -n 1 file
awk 'NR==1' file
を使用することもできますcat file.txt | head -1
が、おそらく のように head を直接使用する方がよいでしょうhead -1 file.txt
。
これは、 では不可能な場合がありますcat
。使用しなければならない理由はありますcat
か?
単純に bash コマンドで実行する必要がある場合は、これでうまくいくはずです。
head -n 1 file.txt
cat
単独では不可能かもしれませんが、これを使用したくない場合は、次のようにhead
機能します。
cat <file> | awk 'NR == 1'
I'm surprised that this question has been around as long as it has, and nobody has provided the pre-mapfile built-in approach yet.
IFS= read -r first_line <file
...puts the first line of the file in the variable expanded by "$first_line"
, easy as that.
Moreover, because read
is built into bash and this usage requires no subshell, it's significantly more efficient than approaches involving subprocesses such as head
or awk
.
bash v4+ を使用している場合、外部コマンドは必要ありません
< file.txt mapfile -n1 && echo ${MAPFILE[0]}
またはあなたが本当にしたい場合cat
cat file.txt | mapfile -n1 && echo ${MAPFILE[0]}
:)
この質問に対する適切な答えはたくさんあります。やりたい場合は、別のものをバスケットに入れるだけですlolcat
lolcat FileName.csv | head -n 1