简体   繁体   English

Bash:处理目录中的所有文件

[英]Bash: process all files in a directory

How would I apply a logic to all files in a directory and pipe the final output of each input file to a separate file?如何将逻辑应用于目录中的所有文件,并将每个输入文件的最终 output pipe 应用于单独的文件? Something like below像下面的东西

cut -d, -f2 input1.csv | awk 'END{print NR}' > input1_count.csv

(actual command is long, but I used above for simplicity to better understand the logic to all the files in a directory) (实际命令很长,但为了简单起见,我在上面使用了以更好地理解目录中所有文件的逻辑)

You can use a for -loop over the filenames:您可以在文件名上使用for循环:

shopt -s nullglob # enable nullglob
for f in *.csv; do
   cut -d, -f2 "$f" | awk 'END{print NR}' > "${f%.csv}_count.csv"
done
shopt -u nullglob # disable nullglob

The glob pattern *.csv expands to a null string with nullglob enabled (instead of a literal and probably non-existing filename *.csv ). glob 模式*.csv扩展为启用nullglob的 null 字符串(而不是文字和可能不存在的文件名*.csv )。 In the loop, apply the pipeline of commands to each filename and redirect the output to a new filename.在循环中,将命令管道应用于每个文件名,并将 output 重定向到新文件名。

The parameter expansion ${f%.csv} removes the shortest suffix pattern .csv from the filename. 参数扩展${f%.csv}从文件名中删除最短后缀模式.csv

A simple for loop should do the job:一个简单for循环应该可以完成这项工作:

for f in *.csv; do
   cut -d, -f2 "$f" | awk 'END{print NR}' > "${f/%.csv/_count.csv}"
done

This assumes you have .csv files are present in current directory.这假设您有.csv文件存在于当前目录中。 If files may not exist then use any of these shopt above for loop:如果文件可能不存在,则使用上面的任何这些shopt for循环:

shopt -s failglob    # return error when glob matching fails

or或者

shopt -s nullglob    # be silent when glob matching fails

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM