user613114 user613114 - 3 months ago 12
Linux Question

Unix cut except last two tokens

I'm trying to parse file names in specific directory. Filenames are of format:

token1_token2_token3_token(N-1)_token(N).sh


I need to cut the tokens using delimiter
'_'
, and need to take string except the last two tokens. In above examlpe output should be
token1_token2_token3
.

The number of tokens is not fixed. I've tried to do it with
-f#-
option of
cut
command, but did not find any solution. Any ideas?

Answer

With cut:

$ echo t1_t2_t3_tn1_tn2.sh | rev | cut -d_ -f3- | rev
t1_t2_t3

The 3- in -f3- means "from N’th field, to end of line"

Comments