英文:
Date extraction from file name in bash
问题
我有一个包含多个文件的目录,文件名的模式是abc12gddmmyyyy.zip。
我正在使用bash脚本工作,想要从文件名中提取模式ddmmyyyy。有人可以帮忙吗?我是Linux环境的新手。谢谢
示例代码
for filename in data/*; do
date=<需要的部分>
echo $date
done
英文:
I am having a directory which contains multiple files with name in pattern abc12gddmmyyyy.zip.
I am working in bash script and I want to extract the pattern ddmmyyyy from the file name. Could anyone please help. I am new to linux enviornment. Thanks
Sample code
for filename in data/*; do
date=<This part needed>
echo $date
done
答案1
得分: 1
使用 sed
可以有许多解决方法:
date="$(echo "$filename" | sed -r 's/^.*12g([0-9]{8})\.zip//')"
英文:
There are, of course, many solutions. One way could be to use sed
:
date="$(echo "$filename" | sed -r 's/^.*12g([0-9]{8})\.zip//')"
答案2
得分: 1
[[ "$filename" =~ (.{8}).zip$ ]] && date="${BASH_REMATCH[1]}"
英文:
With bash and a regex:
[[ "$filename" =~ (.{8})\.zip$ ]] && date="${BASH_REMATCH[1]}"
答案3
得分: 0
files:
ls ./files/
abc12g01022020.zip abc12g02022020.zip
script:
for file in ./files/*
do
echo $file | awk -F'.zip' '{print $1}' | tail -c 9
done
output:
01022020
02022020
Though to be honest it's a bit of a one-use-case scenario you've painted for us.
英文:
files:
ls ./files/
abc12g01022020.zip abc12g02022020.zip
script:
for file in ./files/*
do
echo $file | awk -F'.zip' '{print $1}' | tail -c 9
done
output:
01022020
02022020
Though to be honest it's a bit of a one-use-case scenario you've painted for us.
答案4
得分: 0
这是另一个纯Bash选项:
for filename in data/*.zip; do
date="${filename: -12:8}"
echo "$date"
done
这种方法假设所有文件都正好符合你描述的模式:<random_string>DDMMYYYY.zip
。由于日期从字符串的末尾的第12个字符开始,我们可以提取它作为子字符串。
${parameter:offset:length}
子字符串扩展。从指定的偏移位置开始,将参数扩展为最多 length
个字符。如果 offset
的计算结果小于零,则该值将被视为从参数值的末尾开始的偏移量。
来源:
man bash
注意:要注意的是,形式为 DDMMYYYY
的日期格式不可排序,通常会导致很多烦恼。始终使用可排序的格式,如 YYYYMMDD
,会更有用。
英文:
Here is another pure bash option:
for filename in data/*.zip; do
date="${filename: -12:8}"
echo "$date"
done
This method assumes that all your files have exactly the pattern as you describe: <random_string>DDMMYYYY.zip
. Since the date is starting at the 12th character from the back, we can extract it as a substring.
> ${parameter:offset:length}
Substring Expansion. Expands to up to length
characters of
parameter starting at the character specified by offset
. <snip> If offset
evaluates to a number less than zero, the value is used
as an offset from the end of the value of parameter. <snip>
A negative offset is taken relative to one greater than the max‐
imum index of the specified array. <snip> Note that a
negative offset must be separated from the colon by at least one
space to avoid being confused with the :-
expansion.
> <sub>source: man bash
</sub>
note: be aware that a date-format of the type DDMMYYYY
is not sortable and generally will lead one day to a lot of annoyance. It is always useful to use sortable formats like YYYYMMDD
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论