Results 1 to 3 of 3

Thread: Output redirection to samefile

  1. #1
    Join Date
    Jul 2014
    Location
    Canada
    Beans
    Hidden!
    Distro
    Ubuntu 14.04 Trusty Tahr

    Output redirection to samefile

    Hi,

    I am currently studying the ">" and ">>" tools for output redirection. I have a file, eleves.txt, in which some lines a repeated. My goal is to sort them out. For this, I want to use the sort command. In a terminal, I have written:
    Code:
    sort eleves.txt > eleves.txt
    Now I know that, using the ">" tool for output redirection, if the file already exists, it will be overwritten. My problem is that when I type
    Code:
    cat eleves.txt
    in the terminal (after having sorted the file a redirected the output to the same file), all data from eleves.txt seems to have disapeared. I was expecting the files to have all its lines sorted instead. Please help me understand this behaviour...

  2. #2
    Join Date
    Aug 2011
    Location
    52.5° N 6.4° E
    Beans
    6,820
    Distro
    Xubuntu 22.04 Jammy Jellyfish

    Re: Output redirection to samefile

    >> will append the sorted file, so sort eleves.txt >>eleves.txt leads to a sorted list of (pupils?).
    > will truncate the file to zero and then write the output. It appears that the shell first truncates the file to make it ready for writing and only then starts the sort command, which therefore encounters an empty file, which after sorting still is an empty file. You could try first storing it as a temporary file under a different name.

    If you want to delete repeated lines, have a look at the uniq command. See man uniq.
    Code:
    sort input | uniq >output

  3. #3
    Join Date
    Jul 2014
    Location
    Canada
    Beans
    Hidden!
    Distro
    Ubuntu 14.04 Trusty Tahr

    Re: Output redirection to samefile

    Okay, thanks for the reply!

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •