Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Unix way of looping through space-delimited strings?

Tags:

bash

unix

sh

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?

like image 763
Sibbs Gambling Avatar asked Sep 16 '14 13:09

Sibbs Gambling


People also ask

How do I read a delimited file in Unix?

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.

How do you write a For loop in Unix?

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.

How do I iterate through a list in Bash?

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.


2 Answers

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
like image 130
randomusername Avatar answered Sep 23 '22 15:09

randomusername


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)

Test

$ 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
like image 39
fedorqui 'SO stop harming' Avatar answered Sep 19 '22 15:09

fedorqui 'SO stop harming'