How to get second last field from a cut command

前端 未结 6 2098
南方客
南方客 2020-12-04 19:04

I have a set of data as input and need the second last field based on deleimiter. The lines may have different numbers of delimiter. How can I get second last field ?

6条回答
  •  北海茫月
    2020-12-04 19:50

    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 

    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.

提交回复
热议问题