How to get second last field from a cut command How to get second last field from a cut command unix unix

How to get second last field from a cut command


Got a hint from Unix cut except last two tokens and able to figure out the answer :

cat datafile | rev | cut -d '/' -f 2 | rev


Awk is suited well for this:

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

The variable NF is a special awk variable that contains the number of fields in the current record.


There's no need to use cut, rev, or any other tools external to bash here at all. Just read each line into an array, and pick out the piece you want:

while IFS=, read -r -a entries; do  printf '%s\n' "${entries[${#entries[@]} - 2]}"done <file

Doing this in pure bash is far faster than starting up a pipeline, at least for reasonably small inputs. For large inputs, the better tool is awk.