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 linebasename 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
How to Read Config Files with Section in Bash Shell
Changing Color of Eclipse Links in Quick Fix or Eclipse Links in Preferences on Linux
Restoring Stdout and Stderr to Default Value
Remove All Text from Last Dot in Bash
Running Multiple Compass-Sass Watch Operations Automatically
Arm Assembly "Retne" Instruction
Bash Script to Run a Constant Number of Jobs in the Background
How to Kill a Process on No Output for Some Period of Time
Is There Way to Delete Duplicate Header in a File in Unix
Libpcap - Capture Packets from All Interfaces
Why Do We Need to Call Poll_Wait in Poll
Direct Control of Hci Device (Bypass Bluetooth Drivers) on Linux
Are Pid-Files Still Flawed When Doing It 'Right'
What Is the Use of Gfp_User Flag in Kmalloc
Bluetooth Low Energy:Android Gatt-Client Connect to Linux Gatt Server