2

Suppose there is a file file1.c It has 100 lines . I need to print first word and last word of that file.

5
  • 3
    awk can be awkward, for a 'budget' approach you may want to check head, tail and cut commands. Commented Aug 1, 2018 at 11:35
  • @PS. Please don't answer in comments. This bypasses quality control because people can't both up and down vote comments. Commented Aug 1, 2018 at 12:22
  • @CJDennis understood. Commented Aug 1, 2018 at 12:23
  • 1
    Welcome to Stack Overflow! Please show how you have tried to solve the problem so far so you can be guided. Please also take the site tour and read the help pages. Commented Aug 1, 2018 at 12:23
  • true many linux systems might not have awk installed Commented Mar 19, 2024 at 17:48

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Although this answer is valid, explaining it would greatly improve it's quality. Explain the rev usage.
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
3
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

NR - number of the current record (which equate to the line number :)
0

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/' 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.