Is there any linux command to Keep only 5 recent files that start with REF in a folder? - linux

I would like to make a linux command which will keep only the last 5 recent files, but these files must start with REF, and delete the other files also which start with REF, but not touch the other files.
For example: in my folder, I have:
-rw-r--r-- 1 0 Jan 1, 2022 File_0
-rw-r--r-- 1 0 Jan 1, 2022 REF_1
-rw-r--r-- 1 0 Feb 1 2022 REF_2
-rw-r--r-- 1 0 March 1, 2022 REF_3
-rw-r--r-- 1 0 Apr 1, 2022 REF_4
-rw-r--r-- 1 0 May 1, 2022 REF_5
-rw-r--r-- 1 0 June 1, 2022 REF_6
-rw-r--r-- 1 0 Jul 1, 2022 file_7
-rw-r--r-- 1 0 1 Aug 2022 file_8
-rw-r--r-- 1 0 Sep 1, 2022 REF_9
The command should remove only:
-rw-r--r-- 1 0 Jan 1, 2022 REF_1
-rw-r--r-- 1 0 Feb 1 2022 REF_2
... and should keep the other files. I tried ls -t REF* | head -n+4 | xargs rm REF* but this command deletes all files that start with REF!
What command can I use?

Using zsh (available on many Linux distributions and also on AIX from IBM's AIX Toolbox for Open Source Software), you could simply:
rm REF*(om[6,-1])
This uses zsh's powerful globbing (filename generation) abilities to:
gather the list of files starting with REF
sort the files by their modification time (newest first) with (om...)
keep the five newest files by selecting the 6th and remaining files with [6,-1]
pass that list of files to rm
Test it first with a simple print -l REF*(om[6,-1]) to see which files would be collected.
See Glob Qualifiers for more about zsh's glob qualifiers.

Logrotate was mentioned, why not use it?
It can't handlle the separator being an underscore (_).
$ cat log.conf
REF* {
rotate 5
}
% logrotate log.conf
error: log.conf:1 keyword 'REF' not properly separated, found 0x2a
Here is a complete script, with safe filenames.
find . -name 'REF_*' -print0 | \
xargs -0 stat -c "%Y %n" | \
sort -n | \
head -n+3 | \
sed -e 's/^[0-9]* //' | \
tr '\12' '\0' | \
xargs -0 rm
First, let us use find with nulls to fetch the list of files.
Then use xargs to use stat to prepend the unix time stamp.
Use sort to sort by oldest first.
Use head -n+3 to find all except the last 5.
Use sed to strip the temporary unix time stamp.
Use tr to convert the returns from stat to nulls again.
Finally xargs to delete the unwanted files.

Related

Using variables as the input to command

I've scoured various message boards to understand why I can't use a variable as input to a command in certain scenarios. Is it a STDIN issue/limitation? Why does using echo and here strings fix the problem?
For example,
~$ myvar=$(ls -l)
~$ grep Jan "$myvar"
grep: total 9
-rwxr-xr-x 1 jvp jvp 561 Feb 2 23:59 directoryscript.sh
-rw-rw-rw- 1 jvp jvp 0 Jan 15 10:30 example1
drwxrwxrwx 2 jvp jvp 0 Jan 19 21:54 linuxtutorialwork
-rw-rw-rw- 1 jvp jvp 0 Jan 15 13:08 littlefile
-rw-rw-rw- 1 jvp jvp 0 Jan 19 21:54 man
drwxrwxrwx 2 jvp jvp 0 Feb 2 20:33 projectbackups
-rwxr-xr-x 1 jvp jvp 614 Feb 2 20:41 projectbackup.sh
drwxrwxrwx 2 jvp jvp 0 Feb 2 20:32 projects
-rw-rw-rw- 1 jvp jvp 0 Jan 19 21:54 test1
-rw-rw-rw- 1 jvp jvp 0 Jan 19 21:54 test2
-rw-rw-rw- 1 jvp jvp 0 Jan 19 21:54 test3: File name too long
As you can see I get the error... 'File name too long'
Now, I am able to get this to work by using either:
echo "$myvar" | grep Jan
grep Jan <<< "$myvar"
However, I'm really after a better understanding of why this is the way it is. Perhaps I am missing something about basics of command substitution or what is an acceptable form of STDIN.
The grep utility can operate...
On files the names of which are provided on the command line, after the regular expression used for matching
On a stream supplied on its standard input.
You are doing this :
myvar=$(ls -l)
grep Jan "$myvar"
This provides the content of variable myvar as an argument to the grep command, and since it is not a file name, it does not work.
There are many ways to achieve your goal. Here are a few examples.
Use the content of the variable as a stream connected to the standard input of grep, with one of the following methods (all providing the same output) :
grep Jan <<<"$myvar"
echo "$myvar" | grep Jan
grep Jan < <(echo "$myvar")
Avoid the variable to start with, and send the output of ls directly to grep :
ls -l | grep Jan
grep Jan < <(ls -l)
Provide grep with an expression that actually is a file name :
grep Jan <(ls -l)
The <(ls -l) expression is syntax that causes a FIFO (first-in first-out) special file to be created. The ls -l command sends its output to FIFO. The expression is converted by Bash to an actual file name that can be used for reading.
To clear any confusion, the two statements below (already shown above) look similar, but are fundamentally very different :
grep Jan <(ls -l)
grep Jan < <(ls -l)
In the first one, grep receives a file name as an argument and reads this files. In the second case, the additional < (whitespace between the two < is important) creates a redirection that reads the FIFO and feeds its output to the standard input of grep. There is a FIFO in both cases, but it is presented in a totally different way to the command.
I think there's a fundamental misunderstanding of how Unix tools/Bash operates here.
It appears what you're trying to do here is store the output of ls in a variable (which is something you shouldn't do for other reasons) and trying to grep across the string stored inside that variable using grep.
This is not how grep works. If you look at the man page for grep, it says:
SYNOPSIS
grep [OPTIONS] PATTERN [FILE...]
grep [OPTIONS] [-e PATTERN | -f FILE] [FILE...]
DESCRIPTION
grep searches the named input FILEs for lines containing a match to
the given PATTERN. If no files are specified, or if the file “-” is
given, grep searches standard input. By default, grep prints the
matching lines.
Note that it specifically says "grep searches the named input FILEs".
Then it goes on to say "If no files are specified [...] grep searches standard input".
In other words, by definition grep does not search over strings. It searches files. Therefore you can not pass grep a string, via a bash variable.
When you type
grep Jan "$myvar"
Based on the syntax, grep thinks "Jan" is the PATTERN and the entire string in "$myvar" is a FILEname. Hence the error File name too long.
When you write
echo "$myvar" | grep Jan
What you're now doing is making bash output the contents of "$myvar" to standard output. The | (pipe operator) in bash, connects the stdout (standard output) of the echo command, to the stdin (standard input) of the grep command. As noted above, when you omit the FILEname parameter to grep, it searches for a string in it's stdin by default, which is why this works.
Grep takes as command line parameters files, not direct strings. You do indeed need the echo to make grep search in your variable.

bash tail the newest file in folder without variable

I have a bunch of log files in a folder. When I cd into the folder and look at the files it looks something like this.
$ ls -lhat
-rw-r--r-- 1 root root 5.3K Sep 10 12:22 some_log_c48b72e8.log
-rw-r--r-- 1 root root 5.1M Sep 10 02:51 some_log_cebb6a28.log
-rw-r--r-- 1 root root 1.1K Aug 25 14:21 some_log_edc96130.log
-rw-r--r-- 1 root root 406K Aug 25 14:18 some_log_595c9c50.log
-rw-r--r-- 1 root root 65K Aug 24 16:00 some_log_36d179b3.log
-rw-r--r-- 1 root root 87K Aug 24 13:48 some_log_b29eb255.log
-rw-r--r-- 1 root root 13M Aug 22 11:55 some_log_eae54d84.log
-rw-r--r-- 1 root root 1.8M Aug 12 12:21 some_log_1aef4137.log
I want to look at the most recent messages in the most recent log file. I can now manually copy the name of the most recent log and then perform a tail on it and that will work.
$ tail -n 100 some_log_c48b72e8.log
This does involve manual labor so instead I would like to use bash-fu to do this.
I currently found this way to do it;
filename="$(ls -lat | sed -n 2p | tail -c 30)"; tail -n 100 $filename
It works, but I am bummed out that I need to save data into a variable to do it. Is it possible to do this in bash without saving intermediate results into a variable?
tail -n 100 "$(ls -at | head -n 1)"
You do not need ls to actually print timestamps, you just need to sort by them (ls -t). I added the -a option because it was in your original code, but note that this is not necessary unless your logfiles are "dot files", i.e. starting with a . (which they shouldn't).
Using ls this way saves you from parsing the output with sed and tail -c. (And you should not try to parse the output of ls.) Just pick the first file in the list (head -n 1), which is the newest. Putting it in quotation marks should save you from the more common "problems" like spaces in the filename. (If you have newlines or similar in your filenames, fix your filenames. :-D )
Instead of saving into a variable, you can use command substitution in-place.
A truly ls-free solution:
tail -n 100 < <(
for f in *; do
[[ $f -nt $newest ]] && newest=$f
done
cat "$newest"
)
There's no need to initialize newest, since any file will be newer than the null file named by the empty string.
It's a bit verbose, but it's guaranteed to work with any legal file name. Save it to a shell function for easier use:
tail_latest () {
dir=${1:-.}
size=${2:-100}
for f in "$dir"/*; do
[[ $f -nt $newest ]] && newest=$f
done
tail -f "$size" "$newest"
}
Some examples:
# Default of 100 lines from newest file in the current directory
tail_latest
# 200 lines from the newest file in another directory
tail_latest /some/log/dir 200
A plug for zsh: glob qualifiers let you sort the results of a glob directly, making it much easier to get the newest file.
tail -n 100 *(om[1,1])
om sorts the results by modification time (newest first). [1,1] limits the range of files matched to the first. (I think Y1 should do the same, but it kept giving me an "unknown file attribute" error.)
Without parsing ls, you'd use stat
tail -n 100 "$(stat -c "%Y %n" * | sort -nk1,1 | tail -1 | cut -d" " -f 2-)"
Will break if your filenames contain newlines.
version 2: newlines are OK
tail -n 100 "$(
stat --printf "%Y:%n\0" * |
sort -z -t: -k1,1nr |
{ IFS=: read -d '' time filename; echo "$filename"; }
)"
You can try this way also
ls -1t | head -n 1 | xargs tail -c 50
Explanation :
ls -1rht -- list the files based on modified time in reverse order.
tail -n 1 -- get the last one file
tail -c 50 -- show the last 50 character from the file.

How could I remove all directories except 10 recent with bash?

I have the following folders in my base /var/www/.versions directory:
1435773881 Jul 1 21:04
1435774663 Jul 2 21:17
1435774856 Jul 3 21:20
1435775432 Jul 4 21:56
How could I remove all directories except most 10 recent with bash script?
This should do the trick, I believe?
rm -r $(ls -td /var/www/.versions/*/ | tac | head -n-10)
The idea: list (with ls) only directories ( that's the -d /var/www/.versions/*/) sorted by time with -t (oldest will be shown last).
Then, reverse the output using tac so the oldest directories are on top.
And then show them all except the last 10 lines with head and a negative argument to -n
Please, test with non-vital directories first ;-) You can change the rm -r by echo to see what would be removed.
You could use -rt option in ls for listing in reverse order of time.
rm -r $(ls -trd /var/www/.versions/*/ | head -n -10)
Also, be sure of you put / in the end of /var/www/.versions/*/ and that all directory names do not start with .

How can I list (ls) the 5 last modified files in a directory?

I know ls -t will list all files by modified time. But how can I limit these results to only the last n files?
Try using head or tail. If you want the 5 most-recently modified files:
ls -1t | head -5
The -1 (that's a one) says one file per line and the head says take the first 5 entries.
If you want the last 5 try
ls -1t | tail -5
The accepted answer lists only the filenames, but to get the top 5 files one can also use:
ls -lht | head -6
where:
-l outputs in a list format
-h makes output human readable (i.e. file sizes appear in kb, mb, etc.)
-t sorts output by placing most recently modified file first
head -6 will show 5 files because ls prints the block size in the first line of output.
I think this is a slightly more elegant and possibly more useful approach.
Example output:
total 26960312
-rw-r--r--# 1 user staff 1.2K 11 Jan 11:22 phone2.7.py
-rw-r--r--# 1 user staff 2.7M 10 Jan 15:26 03-cookies-1.pdf
-rw-r--r--# 1 user staff 9.2M 9 Jan 16:21 Wk1_sem.pdf
-rw-r--r--# 1 user staff 502K 8 Jan 10:20 lab-01.pdf
-rw-rw-rw-# 1 user staff 2.0M 5 Jan 22:06 0410-1.wmv
Use tail command:
ls -t | tail -n 5
By default ls -t sorts output from newest to oldest, so the combination of commands to use depends in which direction you want your output to be ordered.
For the newest 5 files ordered from newest to oldest, use head to take the first 5 lines of output:
ls -t | head -n 5
For the newest 5 files ordered from oldest to newest, use the -r switch to reverse ls's sort order, and use tail to take the last 5 lines of output:
ls -tr | tail -n 5
ls -t list files by creation time not last modified time. Use ls -ltc if you want to list files by last modified time from last to first(top to bottom). Thus to list the last n: ls -ltc | head ${n}
None of other answers worked for me. The results were both folders and files, which is not what I would expect.
The solution that worked for me was:
find . -type f -mmin -10 -ls
This lists in the current directory all the files modified in the last 10 minutes. It will not list last 5 files, but I think it might help nevertheless
if you want to watch as it process last five modified file and refresh in 2 secs and show total number of files at top use this:
watch 'ls -Art | wc -l ; ls -ltr | tail -n 5'

One liner to rename bunch of files

I was looking for a linux command line one-liner to rename a bunch of files in one shot.
pattern1.a pattern1.b pattern1.c ...
Once the command is executed I should get
pattern2.a pattern2.b pattern2.c ...
for i in pattern1.*; do mv -- "$i" "${i/pattern1/pattern2}"; done
Before you run it, stick an echo in front of the mv to see what it would do.
If you happen to be using Linux, you may also have a perl script at /usr/bin/rename (sometimes installed as "prename") which can rename files based on more complex patterns than shell globbing permits.
The /usr/bin/rename on one of my systems is documented here. It could be used like this:
rename "s/pattern1/pattern2/" pattern1.*
A number of other Linux environments seem to have a different rename that might be used like this:
rename pattern1 pattern2 pattern1.*
Check man rename on your system for details.
Plenty of ways to skin this cat. If you'd prefer your pattern to be a regex rather than a fileglob, and you'd like to do the change recursively you could use something like this:
find . -print | sed -ne '/^\.\/pattern1\(\..*\)/s//mv "&" "pattern2\1"/p'
As Kerrek suggested with his answer, this one first shows you what it would do. Pipe the output through a shell (i.e. add | sh to the end) once you're comfortable with the commands.
This works for me:
[ghoti#pc ~]$ ls -l foo.*
-rw-r--r-- 1 ghoti wheel 0 Mar 26 13:59 foo.php
-rw-r--r-- 1 ghoti wheel 0 Mar 26 13:59 foo.txt
[ghoti#pc ~]$ find . -print | sed -ne '/^\.\/foo\(\..*\)/s//mv "&" "bar\1"/p'
mv "./foo.txt" "bar.txt"
mv "./foo.php" "bar.php"
[ghoti#pc ~]$ find . -print | sed -ne '/^\.\/foo\(\..*\)/s//mv "&" "bar\1"/p' | sh
[ghoti#pc ~]$ ls -l foo.* bar.*
ls: foo.*: No such file or directory
-rw-r--r-- 1 ghoti wheel 0 Mar 26 13:59 bar.php
-rw-r--r-- 1 ghoti wheel 0 Mar 26 13:59 bar.txt
[ghoti#pc ~]$

Resources