Suppose there is a file file1.c It has 100 lines . I need to print first word and last word of that file.
3 Answers
first word: head -1 file1.c | cut -d" " -f 1
last word: tail -1 file1.c | rev | cut -d" " -f 1 | rev
head -1 print first line
-d stands for delimeter in this case " " (space)
-f 1 first field
tail -1 print last line
rev reverse the input - in this case first rev cause that line is "mirrored" so last field is now first, so we can cut it. Second rev reverse/mirror back the desired field so its readable
2 Comments
Nic3500
Although this answer is valid, explaining it would greatly improve it's quality. Explain the
rev usage.user265906
rev is basicaly used to reverse a line . he is getting the last line with tail . then he is reversing the line with rev. then by using cut he is getting the first word of the reversed line
awk 'NR==1{print $1} END{print $NF}' file1.c NR==1 : means, line number should be 1. END{}: This block will get executed at the last line of the file. $1 : First column $NF: last column. Hope it helps.
1 Comment
David C. Rankin
NR - number of the current record (which equate to the line number :)
awkcan be awkward, for a 'budget' approach you may want to checkhead,tailandcutcommands.