JKC
JKC

Reputation: 2618

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

Upvotes: 0

Views: 1577

Answers (3)

glenn jackman
glenn jackman

Reputation: 246847

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

Upvotes: 2

JScottMiller
JScottMiller

Reputation: 21

I think you're approaching this in the wrong way.

My suggestion: query the total file size using the "stat" command:

stat --format=%s employee.txt 

You can store the result in a variable like this (assuming you're running a Bash shell):

fileSize="$(stat --format=%s employee.txt)"

Now you retrieve the first line (assuming Bash shell again):

firstLine="$(head -n 1 employee.txt)"

Next you retrieve the last line (assuming Bash shell again):

lastLine="$(tail -n 1 employee.txt)"

Now compute the size of the first and the last line and subtract it from the file size:

echo "Total adjusted size is:" $((fileSize - ${#firstLine} - ${#lastLine}))

Upvotes: 0

Hassan Abbas
Hassan Abbas

Reputation: 1316

You can do it through

cat someFilename.txt | wc -c

The first command outputs the content of the file and the second one counts the size of the input.

This does not remove the header and the trailer. For that you can use 'sed' command as before.

Upvotes: 0

Related Questions