Friday, October 28, 2022

[SOLVED] Simple Unix way of looping through space-delimited strings?

Issue

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

  1. load the file into a variable by filenames='cat file_list'
  2. count the number of spaces, N, by tr -cd ' ' <temp_list | wc -c
  3. loop from 1 to N and parse by space each file name out with cut

Is there an easier/more elegant way of doing this?


Solution

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


Answered By - randomusername
Answer Checked By - Terry (WPSolving Volunteer)