I have a file, called file_list
, containing space-delimited strings, each of which is a file name of a file to be processed. I now wish to loop through all the file names and process them one by one. Pseudocode is
for every filename in file_list
process(filename);
end
I have come up with a rather clumsy solution, which is
filenames='cat file_list'
N
, by tr -cd ' ' <temp_list | wc -c
N
and parse by space each file name out with cut
Is there an easier/more elegant way of doing this?
You can use while shell loop to read comma-separated cvs file. IFS variable will set cvs separated to , (comma). The read command will read each line and store data into each field.
The basic syntax of a for loop is: for <variable name> in <a list of items>;do <some command> $<variable name>;done; The variable name will be the variable you specify in the do section and will contain the item in the loop that you're on.
There are two ways to iterate over items of array using For loop. The first way is to use the syntax of For loop where the For loop iterates for each element in the array. The second way is to use the For loop that iterates from index=0 to index=array length and access the array element using index in each iteration.
The easiest way to do it is a classic trick that's been in the bourne shell for a while.
for filename in `cat file_list`; do
# Do stuff here
done
You can change the file to have words be line separated instead of space separated. This way, you can use the typical syntax:
while read line
do
do things with $line
done < file
With tr ' ' '\n' < file
you replace spaces with new lines, so that this should make:
while read line
do
do things with $line
done < <(tr ' ' '\n' < file)
$ cat a
hello this is a set of strings
$ while read line; do echo "line --> $line"; done < <(tr ' ' '\n' < a)
line --> hello
line --> this
line --> is
line --> a
line --> set
line --> of
line --> strings
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With