Friday, 12 July 2013

[Shell Script #2] Read word by word from a file

Shell Script Example #2:
There is one more usecase where we often read word by word from a file, then this shell script is very useful.
The below script takes one input file and outputs the same file. We can add few more functionality to this script based on our usecase.

  1. #!/bin/bash
  2. FILENAME=$1
  3. while read var2
  4. do
  5.   echo "This is $var2"
  6.   done < $FILENAME

How to run: Save the above script with extension ".sh" and run using below command
. file_name.sh input.txt
Example:
input.txt
12 23 34
11 33 55
66 77 99

output:
This is 12
This is 23
This is 34
This is 11
This is 33
This is 55
This is 66
This is 77
This is 99

If you want to access every line at a time, then please check [Shell Script #1] post.
If you want to access only two words at a time, then below change would help.
At line #3, while read var1 var2 
At line #5, echo "This is $var1 $var2"

Similarly, iy you need 3 words at a time, then while read var1 var2 var3.

No comments:

Post a Comment

You might also like

Related Posts Plugin for WordPress, Blogger...