LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   I would like redirect output to files using shell programming (https://www.linuxquestions.org/questions/programming-9/i-would-like-redirect-output-to-files-using-shell-programming-881925/)

ayamkudy 05-21-2011 05:16 AM

I would like redirect output to files using shell programming
 
I have a huge database of students, I would like extract these data and write to individual file for each students.

I am running a loop in shell program (.sh file), the output of each run in the loop need to redirected to a file with variable name.

I tried the following line, but it did not work, where BodyMsg is the data and Rollno is the students roll number.

echo $BodyMsg > $RolNo".html"

catkin 05-21-2011 05:20 AM

Try echo "$BodyMsg" > "$RolNo.html"

theNbomr 05-21-2011 09:37 AM

If you are executing a loop, you may be writing in multiple steps within the loop. Note that the notation for the first write will probably need to be different from the subsequent writes:
Code:

    echo "$data1" > "$studentFile"
    echo "$data2" >> "$studentFile"

Of course your description of the problem ('doesn't work') adds very little substance. Perhaps you could:
  • Post a code sample, in [CODE][/CODE] tags, of course
  • Give a lot more detail about how it didn't work
---- rod.

Nominal Animal 05-21-2011 11:53 AM

Note that you can redirect standard output to a file permanently using
Code:

exec >> file-to-append-to
so you don't need to redirect every individual command.

In your case, you can do e.g.
Code:

#!/bin/sh

# Save original standard output to descriptor 3
exec 3>&1

# Loop over each Name read from standard input:
while read Name ; do

    # Redirect output to append to $Name.html
    exec >> "$Name.html"

    # Do normal output, it will append to $Name.html
    # ...
done

# Restore standard output. This stops further output
# from going into last $Name.html, too.
exec 1>&3


ayamkudy 05-23-2011 08:30 AM

thanks all... it is solved now...

MTK358 05-23-2011 08:51 AM

Mark the thread as solved.


All times are GMT -5. The time now is 08:42 AM.