Shell loop through files - Examples
Run a command on each file
do something (echo) with all .txt files
for f in *.txt; do echo ${f}; done;
Example: Search string ‘ABC’ in all .txt files
for f in *.txt ; do echo --${f}-- ; grep "ABC" ${f} ; done
same loop over files, but using a pipe (reading from standard input), and a while-loop
ls *.txt | while read f; do echo ${f}; done;
do something with a small set of files
for f in file1.txt file2.txt file3.txt; do echo ${f}; done;
file1.txt
file2.txt
file3.txt
same, but separately defined list of files
filelist="file1.txt file2.txt file3.txt"
for f in ${filelist}; do echo ${f}; done;
reading list of files from file 'filelist.txt' (for larger number of files)
ls *.csv > filelist.txt
# define your list of files
for f in `cat filelist.txt`; do echo ${f}; done;
if a line may include spaces better use a while loop:
cat filelist.txt | while read LINE; do echo "${LINE}"; done
loop over filenames, but remove file extension, see
→ basename string split
for f in Data/*.txt; do FILENAME=${f%%.*}; echo ${FILENAME}; done;
Data/fileA .txt
Data/fileB .txt
loop over filenames, but remove file extension and path prefix
for f in Data/*.txt ; do FILENAME=`basename ${f%%.*}`; echo ${FILENAME}; done
Data/ fileA .txt
Data/ fileB .txt