[英]Loop Through List of Files in Bash
I have a list of files that I get by executing this: ls core_* | sort -n -t _ -k 2
我有一个通过执行此命令获得的文件列表:
ls core_* | sort -n -t _ -k 2
ls core_* | sort -n -t _ -k 2
which gives me something like this:这给了我这样的东西:
core_20171201142359.csv core_20171202131548.csv core_20171203141112.csv
The objective is to get a single file in which to append all the content of every single file in order.目标是获得一个文件,在该文件中按顺序附加每个文件的所有内容。
So, I want to open every single file one by one, copy its content into another file, move the previous source file to another directory for safekeeping and move on.所以,我想一个一个地打开每个文件,将其内容复制到另一个文件中,将前一个源文件移动到另一个目录以妥善保管并继续。
To always get the very first file in order I use ls core_* | sort -n -t _ -k 2 | head -1
为了始终按顺序获取第一个文件,我使用
ls core_* | sort -n -t _ -k 2 | head -1
ls core_* | sort -n -t _ -k 2 | head -1
ls core_* | sort -n -t _ -k 2 | head -1
, and I need to cycle all of those files. ls core_* | sort -n -t _ -k 2 | head -1
,我需要循环所有这些文件。
How can I know when there are no more files that I need to process?我如何知道何时不再需要处理文件?
You can try this:你可以试试这个:
ls core_* | sort -n -t _ -k 2 | while read f; do cat $f >> total.csv; done
Also alongside with cat
you can perform move
etc.与
cat
一起,您还可以执行move
等操作。
For bash, you can store the filenames in an array:对于 bash,您可以将文件名存储在一个数组中:
files=(core_*)
Then the first entry is然后第一个条目是
first="${files[0]}"
And you can iterate with this (the quotes are absolutely required)你可以迭代这个(引号是绝对需要的)
for file in "${files[@]}"; do
echo "$file"
done
Or, if you need to do something with all the files at once:或者,如果您需要一次处理所有文件:
cat "${files[@]}" > core_all.csv
but if that's the case, you don't need to store them at all但如果是这样,你根本不需要存储它们
cat core_* > core_all.csv
for file in $(ls core_* | sort -n -t _ -k 2)
do
cat ${file} >> one_big_file.csv
mv ${file} /anywhere/you/want
done
Will read each file, copy all lines into one_big_file.csv, remove just read file to the /anywhere/you/want将读取每个文件,将所有行复制到 one_big_file.csv 中,将刚刚读取的文件删除到 /anywhere/you/want
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.