Unix cut except last two tokens

Deadly 提交于 2020-01-12 11:47:38

问题


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?


回答1:


With cut:

$ 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).




回答2:


You may use POSIX defined parameter substitution:

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



回答3:


It can not be done with cut, How ever you can use sed or awk

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



回答4:


Just a different way to write ysth's answer

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



来源:https://stackoverflow.com/questions/14010414/unix-cut-except-last-two-tokens

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!