bash 除最后两个标记外的 Unix 剪切
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/14010414/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unix cut except last two tokens
提问by user613114
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.
我需要使用 delimiter 剪切标记'_',并且需要取除最后两个标记之外的字符串。在上面的例子中输出应该是token1_token2_token3.
The number of tokens is not fixed. I've tried to do it with -f#-option of cutcommand, but did not find any solution. Any ideas?
代币数量不固定。我试图用命令-f#-选项来做cut,但没有找到任何解决方案。有任何想法吗?
回答by ysth
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).
rev 反转每一行。的3-在-f3-从所述第三字段到行的结尾(这是通过第三到最后一个字段在非反转文本的行的开始)的装置。
回答by Rubens
You may use POSIX defined parameter substitution:
您可以使用 POSIX 定义的参数替换:
$ name="t1_t2_t3_tn1_tn2.sh"
$ name=${name%_*_*}
$ echo $name
t1_t2_t3
回答by Shiplu Mokaddim
It can not be done with cut, How ever you can use sedor awk
它不能用cut, 你怎么能使用sed或awk
sed -r 's/(_[^_]+){2}$//g'
回答by Rahul
Just a different way to write ysth's answer
只是一种写 ysth 答案的不同方式
echo "t1_t2_t3_tn1_tn2.sh" |rev| cut -d"_" -f1,2 --complement | rev
echo "t1_t2_t3_tn1_tn2.sh" |rev| cut -d"_" -f1,2 --complement | 转

