Loop Over File Names from 'Find'

loop over files and extract part of filename

Just re-assign the loop variable at the beginning of each iteration:

for sample in *.vcf; do
sample=${sample%_*}
# do stuff here
done

How to loop over files in directory and change path and add suffix to filename

A couple of notes first: when you use Data/data1.txt as an argument, should it really be /Data/data1.txt (with a leading slash)? Also, should the outer loop scan only for .txt files, or all files in /Data? Here's an answer, assuming /Data/data1.txt and .txt files only:

#!/bin/bash
for filename in /Data/*.txt; do
for ((i=0; i<=3; i++)); do
./MyProgram.exe "$filename" "Logs/$(basename "$filename" .txt)_Log$i.txt"
done
done

Notes:

  • /Data/*.txt expands to the paths of the text files in /Data (including the /Data/ part)
  • $( ... ) runs a shell command and inserts its output at that point in the command line
  • basename somepath .txt outputs the base part of somepath, with .txt removed from the end (e.g. /Data/file.txt -> file)

If you needed to run MyProgram with Data/file.txt instead of /Data/file.txt, use "${filename#/}" to remove the leading slash. On the other hand, if it's really Data not /Data you want to scan, just use for filename in Data/*.txt.

Loop over file names from `find`?

For this, use the read builtin:

sudo find . -name *.mp3 |
while read filename
do
echo "$filename" # ... or any other command using $filename
done

Provided that your filenames don't use the newline (\n) character, this should work fine.

Loop over file names in a folder and return file name if a key word is in the file

You could try with this, by creating a list of files that have the key:

def search_txt(path, keyWord):
lsfiles=[]
for file in list_file_name(path):
if file.endswith('txt'):
with open(path + '/' + file, 'r') as f:
openFile = f.read()
if keyWord in openFile:
lsfiles.append(file)
if len(lsfiles)==0:
return('No key word found ')
else:
return('Key word {} is in {}'.format(keyWord, ', '.join(lsfiles)))



Related Topics



Leave a reply



Submit