user265906
user265906

Reputation: 160

How to print first word of first line and last word of last line in unix in a file

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

Answers (3)

Walter A
Walter A

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

lojza
lojza

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

P....
P....

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

Related Questions