Shell Script to execute a command on every line of a file

There are many times, where you want to execute the same command every line of a file, it can be simple printing on the screen or some other manipulation. This simple shell script reads a file line by line and executes the command specified by the user on the line.

$ cat execute_command_per_line.sh
if [ $# -ne 2 ]
then
   echo "Usage: execute_command_per_line command filename"
   exit 1
fi

command=$1
filename=$2

while read line
do
   $command $line
done < $filename

As you can see that it takes two parameters,

  1. Command to be executed
  2. Name of the file

Let’s use a simple command like echo, The file contents are as follows

$ cat system_calls.txt
 
aa_change_hat
accept
accept4
access
acct
add_key
adjtime
adjtimex
afs_syscall
alarm

Let’s run the above script

$ ./execute_command_per_line.sh echo system_calls.txt 
aa_change_hat
accept
accept4
access
acct
add_key
adjtime
adjtimex
afs_syscall
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s