This question already has an answer here:

I am having a requirement where I need to extract couple of fields from a file with last field. structure of file can be different so cannot hardcode the last field. lets take example of two different files



another file File2


requirement can be like extract 1st and last field from file1 or requirement can be like extract 2nd and last field from file2

We get this requirement from a configuration table where they mention which field they want to extract but last field is common. one way is to use while loop but with out while loop is there any way that we can achieve this?

marked as duplicate by agc, Jeff Schaller May 22 at 19:14

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Please specify whether or not each file must have the same number of fields within that one file. (For example, the output of this: printf '%s\n' a,b d,e,f has 2 fields in line #1, and 3 fields in line #2.) – agc May 22 at 11:51

Use awk:

awk -F, '{print $1,$NF}' file

These 2 examples should put you on track :

echo {a..z} | awk '{print $1" "$NF}'

a=1; b=5; echo {a..z} | awk -v a=$a -v b=$b '{print $a" "$b}'

In your case, usage would be like :

awk <options> myFile
  • The awk $n variable is the n-th field of the input line.
  • NF is the number of fields, then $NF is the last field of the line
  • you may also specify the input field separator with -F<character>. Here, it would be : -F,
  • Note that the default output separator already is a space, so you could write print $a, $b instead of print $a" "$b (which looks a bit awkward). This would also make it possible for the user to specify a custom separator with -v OFS="somevalue". – Kusalananda May 22 at 13:17

Lower level software tools method, using bash, paste, cut, and rev:

paste -d, <(cut -d, -f1 File1) <(rev File1 | cut -d, -f1 | rev)



Note: rev is needed due to the inability of cut to extract an unspecified last column. But cut can always extract the first column, so rev supplies that.

Not the answer you're looking for? Browse other questions tagged or ask your own question.