How do I redirect command output to a file?

29,880

Solution 1

It's a bad idea to parse the output of ls. The primary job of ls is to list the attributes of files (size, date, etc.). The shell itself is perfectly capable of listing the contents of a directory, with wildcards.

It's quite simple to run md5sum on all the files in the current directory and put the output in a file: redirect its output to the desired output file.

md5sum * >/tmp/md5sums.txt

If you want the output to be sorted by file name, pipe the output of md5sum into sort.

md5sum * | sort -k 2 >/tmp/md5sums.txt

Note that numeric sorting (-n) will only give useful results if the file names are purely numeric. If all you need is for the output to be deterministic, how you sort doesn't matter.

Solution 2

output redirecting is done by below command

commandname > filename
Share:
29,880

Related videos on Youtube

Zac Anderson
Author by

Zac Anderson

Updated on September 18, 2022

Comments

  • Zac Anderson
    Zac Anderson almost 2 years

    I have a command that I run in a folder that outputs MD5 hashes and filenames on the terminal:

    ls |sort -nr | xargs md5sum
    

    I need this output in a text file that I can download and compare to another folder on another customer's machine. How can I modify the command such that its output is stored in a file in say /tmp? I'm using Redhat 5.

  • Zac Anderson
    Zac Anderson over 12 years
    I believe I tried this and it just sat and hung. I broke out of the command and went to the folder I was sending the file to, /tmp, and no file exists with the name I gave it. Here is what I typed: ls |sort -nr | xargs md5sum > /tmp/zac.txt
  • Zac Anderson
    Zac Anderson over 12 years
    Let me give this a try tomorrow and report back. My goal is to get the output from two supposed dirs on two diff servers and then do a diff on each file crossing my fingers they are the same. :) Thanks.
  • Gilles 'SO- stop being evil'
    Gilles 'SO- stop being evil' over 12 years
    @ZacAnderson If you have network connectivity between the two servers, there are easier ways to check that they're the same, e.g. rsync -van /local/path remoteserver:/remote/path (remove the -n to overwrite the remote files with the local files).
  • Zac Anderson
    Zac Anderson over 12 years
    do I have to issue an ssh in there somewhere for the remote server or just put the IP in for the 'remoteserver'.
  • Zac Anderson
    Zac Anderson over 12 years
    the command you noted above with the md5sum into the sort will work for me. I had to put a space between the > and the / but it gave me the file, populated. I will then take the file from server A and then from server B and do a diff on them to see if they are the same. I'm nervous about the rsync command so I'm going to pass on that. Thanks for your help!