我目前正在学习 Linux bash 脚本:
我的文件夹中有具有以下文件名模式的文件:
ABC01_-12ab_STRINGONE_logicMatches.txt
DEF02_-12ab_STRINGTWO_logicMatches.txt
JKL03_-12ab_STRINGTHREE_logicMatches.txt
我想将 STRINGONE、STRINGTWO 和 STRINGTHREE 提取为列表。为了看看我的想法是否有效,我想先将我的结果回显到 bash。
我的 bash 脚本的代码(在文件所在的文件夹中执行):
#!/bin/bash
for element in 'folder' do out='cut -d "_" -f2 $element | echo $out' done
实际结果:
error: unexpected end of file
期望的结果:
STRINGONE
STRINGTWO
STRINGTHREE
(echoed in bash)
最佳答案
你的想法是对的。但是文件通配(查找文本文件)和命令替换(运行 cut
命令)的语法是错误的。你需要做
for file in folder/*.txt;
# This condition handles the loop exit if no .txt files are found, and
# not throw errors
[ -f "$file" ] || continue
# The command-substitution syntax $(..) runs the command and returns the
# result out to the variable 'out'
out=$(cut -d "_" -f3 <<< "$file")
echo "$out"
done
关于Linux:从文件名中获取特定字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46974041/