You are here:

Unix Shell Scripting/Loop through file in directory


Hi I am new to learning how to write shell scripts. I have been trying to figure out how to create a loop that searches a directory for files, if files are found, read in the first line of each file and store them in a variable. I am unsure of how to get started other then using the find command. Could you assist me. Here is my psuedo code.

find "C:Test" (*) -name f
while read f(
//read first line of file
//store line in $variable

There are two parts to your question:

1) To build a list of files to process

2) to read the first line of each

If the files are all in the current directory the list of files is simply: *

Or, if you want a selection of those files, use, for example:
  *.txt # for all files ending with .txt
  *xxx* # for all files whose name contains xxx 

To loop through the files, use a for loop and read the first line into your variable :
 for file in *.txt
   read -r line < "$file"
   : do whatever with variable "$line"

If all you wanted to do was display the first lines, you could use:
 head -n1 *.txt

Unix Shell Scripting

All Answers

Answers by Expert:

Ask Experts


Chris F.A. Johnson


I can answer any questions on using and programming the Unix shell, including the standard POSIX shell and bash.


I have been writing shell programs since 1990 and have written two books on the subject, both published by Apress.

Pro Bash Programming:Scripting the GNU/Linux Shell, Apress 2009 Shell Scripting Recipes: A Problem-Solution Approach, Apress 2005

I completed a Unix systems administrator course given by AT&T Canada.

©2016 All rights reserved.