I want to run wc -l
and use the result in an arithmetic expansion. In other words, I want to do something like this:
wc -l (now somehow pipe/pass the result of this to) $((2 + result of wc command))
How can I do this?
Context
In my ~/Pictures
directory, I have multiple files named "Screenshot from YYYY-MM-DD hh-mm-ss.png
", as well as other files.
I want to keep all files that are not Screenshots, and only a specified number of Screenshot pictures, based on how recent they were. I want to basically only keep the last 3 most recent Screenshots I have, and delete all the rest.
So here is what I have so far:
ls | grep "Screenshot *" | sort -r | wc -l
What I then wanted to do was to subtract 3 from wc -l
, which would then allow me to use tail
to list all the files that are not the first 3, and then just delete them.
For what you are asking (source):
bash -c 'commands'
run a new bash environment, where$1
is an argument given byxargs
. Useman the_commmand
to access manual pages and learn more about each command and their options.From
man bash
:So in this case you could avoid using the placeholder
args
(note you can use any word) just using $0 instead. Also, for justwc -l
you can avoid the-n 1
:For what you need might be more suitable to remove interactively (
-i
) files older than eg 20 days.To get the first 3 newest files with that name pattern is more simple:
Assuming FILE is a file that is located in the current directory:
wc -l < FILE
returns the number of lines in FILE andecho $((`wc -l < FILE` +2))
returns the number of lines in FILE + 2.Translating a string into a numerical expression is relatively straightforward using arithmetic expansion of the form
$((EXPRESSION))
whereEXPRESSION
is an arithmetic expression.