我是正则表达式的新手。在 unix
系统中读取文件需要帮助。我想在 ls
命令上应用正则表达式。
我有以下文件:
DLERMS08001708161708209683.csv.gz
DLERMS13001708161330170816.csv.gz
DLERMS13001708171330170816.csv.gz
并想提取第 11 条记录到第 16 位数字之间有 170816 的文件。
我尝试使用以下命令 ls *170816*.gz
。但是我得到 3 个文件名而不是两个。我只想要前两个文件名,而不是所有 3 个文件名。你能帮忙吗?
还想在这里补充一点,我的第三个文件名末尾已经包含 170816 DLERMS13001708171330170816
.csv.gz。我想在我的 ls
命令输出中避免这种情况。
最佳答案
单独使用 bash
参数扩展,
for file in *.csv.gz; do
[ -e "$file" ] || continue
[ "${file:10:6}" == "170816" ] && printf "%s\n" "$file"
done
${PARAMETER:OFFSET:LENGTH}
This one can expand only a part of a parameter's value, given a position to start and maybe a length. If
LENGTH
is omitted, the parameter will be expanded up to the end of the string. IfLENGTH
is negative, it's taken as a second offset into the string, counting from the end of the string
根据下面的评论,显然 OP 想要将文件复制到备用路径,在这种情况下,printf()
应该替换为 cp
参数
[ "${file:10:6}" == "170816" ] && cp -- "$file" path/to/destination
关于regex - "11th to 16th letter"的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45839909/