Reputation: 160
Suppose there is a file file1.c It has 100 lines . I need to print first word and last word of that file.
Upvotes: 2
Views: 4141
Reputation: 19982
Translate the file to one line and remove everything between the first and last space:
tr -d "\n" < file1.c| sed 's/ .* / /'
When you file starts or ends with a space, this won't work. You can fix that with the more complicated
tr -d "\n" < file1.c| sed -r 's/[ ]*([^ ]+).*([^ ]+)/\1 \2/'
Upvotes: 0
Reputation: 1891
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
Upvotes: 4
Reputation: 18351
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.
Upvotes: 2