问题描述
在bash中,我想提取许多文件名的一部分并将该输出保存到另一个文件中.
In bash I would like to extract part of many filenames and save that output to another file.
文件的格式为coffee_ {我想输入一些数字} .freqdist.
The files are formatted as coffee_{SOME NUMBERS I WANT}.freqdist.
#!/bin/sh
for f in $(find . -name 'coffee*.freqdist)
该代码将找到所有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?
我知道写文件一会以以下结尾.
I know that to write to file one would end the line with the following.
> log.txt
尽管缺少如何过滤文件名列表的中间部分,但我仍然缺少.
I'm missing the middle part though of how to filter the list of filenames.
推荐答案
您可以在bash
中以本机方式进行操作,如下所示:
You can do it natively in bash
as follows:
filename=coffee_1234.freqdist
tmp=${filename#*_}
num=${tmp%.*}
echo "$num"
这是一个纯bash解决方案.不涉及任何外部命令(如sed
),因此速度更快.
This is a pure bash solution. No external commands (like sed
) are involved, so this is faster.
使用以下命令将这些数字附加到文件中:
Append these numbers to a file using:
echo "$num" >> file
(开始循环之前,您需要删除/清除文件.)
(You will need to delete/clear the file before you start your loop.)
这篇关于提取文件名Shell脚本的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!