user2233540
user2233540

Reputation: 447

Display the file's name without its root in Shell Script

I have two questions about Shell Script. I'm doing a simple script to display a list of files greater than a number that is passed as argument.

find $1 -size +$2c -exec ls -lh {} \;| awk '{print $9 -> $5}'  

where $1 is the root, $2 is the size, $9 and $5 are the name of the file and its size respectively.

First question: Is there a way to display the file's name without its root? I just want the name of the file. Second question: Is there a way, in case I don't specify the root, the shell script takes the actual root?

Upvotes: 0

Views: 388

Answers (2)

Christopher Neylan
Christopher Neylan

Reputation: 8272

You can't tell ls to only print the basename of the file. However, you can use the -printf action of find to print the size and basename:

find $1 -size +$2c -printf "%f -> %s\n" 

If you want the sizes in a human-readable format, one way would be to only use find to locate your desired files and then print the basename and size for each result:

find $1 -size +$2c | while read file; do echo $(basename "$file") "->" $(ls -lh "$file" | awk '{print $5}') ; done

EDIT:

Printing a total at the end means building a total within the loop:

#! /bin/bash
total=0
while read file; do
    total=$(($total+$(ls -l "$file" | awk '{print $5}')))
    echo $(basename "$file") "->" $(ls -lh "$file" | awk '{print $5}')
done < <(find $1 -size +$2c)
echo $total

Upvotes: 1

Andy Lester
Andy Lester

Reputation: 93735

Sounds like you want the basename command.

$ basename /foo/bar/bat/baz/whatever.txt
whatever.txt

Upvotes: 0

Related Questions