Command Line Linux Tips and Tricks

Compress a directory

tar -zcvf file-name.tar.gz directory-name

Uncompress a tar.gz file

tar -zxvf compress-file.tar.gz

Uncompress .gz file

gunzip compress-file.gz

or

gzip -d compress-file.gz

List the last modified files in a specific directory recursively

Find the last 10 modified files from a certain directory recursively:

find . -type f -printf '%T@ %p\n' | sort -k1,1nr | head -10

List all files older than x days recursively

Find the files older than 15 days in the current directory and subdirectories:

find . -type f -mtime +15

If you want to delete the files:

find . -type f -mtime +15 -delete

List all files newer than x days recursively

Find the files newer than 15 days in the current directory and subdirectories:

find . -type f -mtime -15

Recursively Search All Files For A String

Find all the files that contain the “foo” string in the current directory and in its subdirectories:

grep -ri -l "foo" .

Print a file, excluding comments and blank lines

grep -v '^$\|^\s*\#' file

To see the crontab

grep -v '^$\|^\s*\#' temp

To remove the time configuration in each line (to copy and paste the crontab commands to the console)

crontab -l | grep -v '^$\|^\s*\#' | cut -d" " -f6-

Restore a MySQL database with different name

First I have to create the backup from the old_database_name

mysqldump -uroot -p --routines --triggers old_database_name > database_backup.sql

Then I have to restore the backup in a new database: new_database_name

mysql -uroot -p -A -Dnew_database_name < database_backup.sql

Delete commented or empty lines in a file

sed -i '/^[@#]/ d' file.txt
sed -i -rn '/\S/p' file.txt

:wq