bash 提取文件名 shell 脚本的一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12582103/
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
Extract part of a filename shell script
提问by mac389
In bash I would like to extract part of many filenames and save that output to another file.
在 bash 中,我想提取许多文件名的一部分并将该输出保存到另一个文件中。
The files are formatted as coffee_{SOME NUMBERS I WANT}.freqdist.
这些文件的格式为 coffee_{SOME NUMBERS I WANT}.freqdist。
#!/bin/sh
for f in $(find . -name 'coffee*.freqdist)
That code will find all the coffee_{SOME NUMBERS I WANT}.freqdist file. Now, how do I make an array containing just {SOME NUMBERS I WANT} and write that to file?
该代码将找到所有的 coffee_{SOME NUMBERS I WANT}.freqdist 文件。现在,我如何制作一个只包含 {SOME NUMBERS I WANT} 的数组并将其写入文件?
I know that to write to file one would end the line with the following.
我知道写入文件 one 会以以下内容结束该行。
> log.txt
I'm missing the middle part though of how to filter the list of filenames.
我错过了如何过滤文件名列表的中间部分。
回答by dogbane
You can do it natively in bash
as follows:
您可以bash
按以下方式在本机上执行此操作:
filename=coffee_1234.freqdist
tmp=${filename#*_}
num=${tmp%.*}
echo "$num"
This is a pure bash solution. No external commands (like sed
) are involved, so this is faster.
这是一个纯粹的 bash 解决方案。不sed
涉及外部命令(如),因此速度更快。
Append these numbers to a file using:
使用以下命令将这些数字附加到文件中:
echo "$num" >> file
(You will need to delete/clear the file before you start your loop.)
(在开始循环之前,您需要删除/清除文件。)
回答by Guru
If the intention is just to write the numbers to a file, you do not need find command:
如果只是将数字写入文件,则不需要 find 命令:
ls coffee*.freqdist
coffee112.freqdist coffee12.freqdist coffee234.freqdist
The below should do it which can then be re-directed to a file:
下面应该这样做,然后可以重定向到一个文件:
$ ls coffee*.freqdist | sed 's/coffee\(.*\)\.freqdist//'
112
12
234
Guru.
大师。
回答by James Waldby - jwpat7
The previous answers have indicated some necessary techniques. This answer organizes the pipeline in a simple way that might apply to other jobs as well. (If your sed
doesn't support ‘;' as a separator, replace ‘;' with ‘|sed'.)
前面的答案已经指出了一些必要的技巧。这个答案以一种可能也适用于其他工作的简单方式组织了管道。(如果您sed
不支持 ';' 作为分隔符,请将 ';' 替换为 '|sed'。)
$ ls */c*; ls c*
fee/coffee_2343.freqdist
coffee_18z8.x.freqdist coffee_512.freqdist coffee_707.freqdist
$ find . -name 'coffee*.freqdist' | sed 's/.*coffee_//; s/[.].*//' > outfile
$ cat outfile
512
18z8
2343
707