user613114
user613114

Reputation: 2821

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?

Upvotes: 29

Views: 22127

Answers (4)

ysth
ysth

Reputation: 98398

You can truncate the string at the second to last _ using cut with rev:

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

rev reverses each line. The 3- in -f3- means from the 3rd field to the end of the line (which is the beginning of the line through the third-to-last field in the unreversed text).

Upvotes: 57

Rahul
Rahul

Reputation: 2384

Just a different way to write ysth's answer :

echo "t1_t2_t3_tn1_tn2.sh" |rev| cut -d"_" -f1,2 --complement | rev

Upvotes: 1

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57660

It can not be done with cut, However, you can use sed

sed -r 's/(_[^_]+){2}$//g'

Upvotes: 8

Rubens
Rubens

Reputation: 14778

You may use POSIX defined parameter substitution:

$ name="t1_t2_t3_tn1_tn2.sh"
$ name=${name%_*_*}
$ echo $name
t1_t2_t3

Upvotes: 7

Related Questions