LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Trying to write a bash script need some suggesstions. (https://www.linuxquestions.org/questions/linux-newbie-8/trying-to-write-a-bash-script-need-some-suggesstions-4175463925/)

ajaylinuxrk 05-29-2013 07:03 AM

Trying to write a bash script need some suggesstions.
 
Gurus,

I want to write a bash script to read a line by line from a file and execute in a command and redirect the output to a file.I am able to think through the below syntax but not sure how to redirect the output of the command to another file.Need suggestions.

#/bin/bash

for i in "cat /tmp/file"
do
command | grep "$i"

done.

Thanks in Advance.

shivaa 05-29-2013 07:07 AM

Just try:
Code:

#/bin/bash
while read -r i
do
command | grep "$i" > /path/to/output.txt
done < /tmp/file

Use while+read instead of for loop for reading output from a file line by line. The > /path/to/output.txt part redirects output of the command into a file named /path/to/output.txt.

chrism01 05-29-2013 07:12 AM

Given that each cmd is tun separately, you probably want '>>' i.e. append, instead of > (output), which will overwrite the file.

Habitual 05-29-2013 11:11 AM

Code:

REPORT=/home/c9admin/amn_ami_delete3.rpt
... stuff...
... stuff...
echo "" > "$REPORT" #truncates "$REPORT"
... stuff...
        do ec2-deregister $i >> "$REPORT" # appends output of each iteration into "$REPORT"


grail 05-29-2013 12:00 PM

A slight alternative to shivaa's example and allowing the incorporation of chrism01's suggestion:
Code:

while read -r line
do
    command | grep "$line"
done< /tmp/file > /path/to/output.txt


David the H. 05-30-2013 06:32 PM

If the "command" prints the same output every time, and you just want to capture all the matching lines from the file, then this would probably do you better:

Code:

command | grep -f /tmp/file > /path/to/output.txt


All times are GMT -5. The time now is 07:37 AM.