Search code examples
unixsedls

Unix - How do you pass / pipe the output of a sed command to a ls command in Unix


I am able to determine the size of an input file using the following command :

ls -l employee.txt | awk '{print $5}'

This will print only the file size.

And I am able to print the contents of a file ignoring first and last line (refers to header & trailer) of the file. Below command does this work for me :

sed '1d;$d' employee.txt

But how to combine both these commands in such a way that it should determine the size of the file ignoring header and trailer. At the same time the header and trailer should not be removed from the input file.

I am able to achieve this by writing two statements. One to copy the full file into a new file except header and trailer and then doing a ls on the new file as below :

sed '1d;$d' employee.txt > employee1.txt

ls -l employee1.txt

I tried to do it in a single statement as below but to no avail. Any inputs will be helpful.

sed '1d;$d' employee.txt | ls -l employee.txt

ls -l `sed '1d;$d' employee.txt`

sed '1d;$d' employee.txt |xargs ls -l $1

Solution

  • Don't parse ls to get the file size. To get the size of a file on disk, use stat -c '%s' filename, or to get the size of a stream of characters, use wc -c.

    # size of employee.txt
    stat -c '%s' employee.txt
    
    # size without header and footer
    sed '1d;$d' employee.txt | wc -c