How to Delete Lines in Vim / Vi

Vim comes out as an outstanding tool that helps to configure files and editing text mostly under Linux. One quirk of Vim that many cannot acknowledge is its capability to delete or erase complete lines in a text or file. Nothing complex about Vim but learning it is definitely useful.

Like every other work, deleting a line in Vim too has various methods. Vim, the widely known editor for text in Linux, can undo one or many patterns in a single command.

This tutorial will help you get knowledge on deleting lines by range or pattern by various options provided by Vim.

Various ways to delete a line in Vim

How to delete a single line?

  • Press on the Esc key and rapidly move along different files.
  • Move the cursor towards your line of choice for deleting.
  • If you want to delete a line, you need to press one of the following commands,
DD
D

Deleting a single word

  • Pressing Esc helps you enter the mode of command.
  • Next step involves the pointer being placed at the start of the very word.
  • Press down on the key that instant.

Steps for deleting multiple rows?

  • Start by pressing the Esc key.
  • Next step involves moving pointer to the line that’s needed to get deleted.
  • One use of one of the below mentioned commands the line will get deleted
[#]d d {# stands for no. of lines}
D-d-d

Method for deleting series’ of lines

  • Start by using the Esc key to enter a normal mode in Vim.
  • The following command will be brought to use with the beginning of the line’s range to the end of the line’s spectrum.

Example for reference is, deleting lines 3, 4, 5, and 6 by using the command: 2,6d.

Methodology for – delete all rows.

  • Firstly you press the Esc key.
  • Finally clear out everything inside the file by command, %d.
  • Once this command is executed, Vim will pop up, “No lines in buffer”.

Deleting the line present at the end of the file

Firstly the person needs to be moved to the line that needs deletion.
Entering command mode is followed by pressing of the Esc key.
The last step is to getting deleted every line except the ones you want to keep. The command needed: $d.

Deleting the line present at the beginning of the file

The first thing is to position the cursor properly on the line that needs deletion.
I am following with pressing the escape key.
Finally using the command delete the line at the beginning of the file.

Steps for deleting template-based lines

Vim allows you to get the lines with the coincidence of patterns. Many ways are available for deleting template-based lines. There are several ways to delete rows based on a template.

Deleting line laced with the specific word

  • Bring to use the Esc key and enter yourself into the mode of normality in the text.
  • You can delete the line with a specific word using, r / word/.

Getting lines lacking specific words deleted

  • Esc key will help you enter in command mode.
  • Use a particular command, r!/word/. To delete like lacking a specific word.

The process to delete the empty lines.

  • Blank lines can be deleted using the Esc key and switching to the normal mode.
  • Following above, enter the mentioned command will do the trick - r/^$/d

When does vim delete every line?

You get to delete a Vim/V line using: 1,$d. When you decide to delete all lines in vi go for: 1, here $ is symbolic of the line which is next in the command. Once a line starts with:g/^$/d it has the potential to delete all empty lines. ^$ present is the resemblance of the empty lines present. The command: g/^s/\*$/d, is capable of deleting every empty line present.

Conclusion

Once you have gone through the above article and have come to acknowledge the analysis well, you will have yourself many choices as to how you can delete a line or word on Vim.
Once you are well aware of Vim’s different commands, you will come to realise how time-efficient Vim will turn out to be.

How to Convert String into Integer in Python

Objects can be any kind of data type in Python, i.e. integer and string. Sometimes, you will need to convert one data form to another while writing Python code. For example, it needs to be transformed into an integer to perform a math operation on a number represented as a string. Here’s how to convert a string in Python to an integer.

int() function in Python

The built-in function int() returns an integer decimal object from a given number or String. It takes the form below:
int(a, base=10)

Two arguments are accepted by the function:

  • a – The number or String to be transformed to an integer.
  • base – Reflects the first argument’s numeral scheme. It can have a value between 0 and 2–36. It is optional to render this statement. The default base is always 10 if no base is defined (decimal integer). Integers are usually expressed in hexadecimal format i.e., base 16, decimal has base 10, octal has base 8, and binary has base 2.

If the given string cannot be interpreted as an integer, the ValueError exception is executed by the function.

Converting a String to Integer in Python

A ‘string’ is a list of characters declared in Python using a single (‘), double (“), or triple quotes (“””). If you use quotes to declare a variable that contains only numbers, its data type is set to String. Consider the instance below:

no_of_day = "23"
type(no_of_day)

The type() function tells us that the String object is the no_of_day variable.

<type 'str' > type

Let’s try on the variable to do a math operation:

print(day+5)

After that, Python throws an exception, i.e., TypeError, because it is unable to perform a string and integer addition calculation:

Traceback (last call last):
'' file, line 1, in
TypeError: can't concatenate items with 'str' and 'int.'

To convert a string representation of a decimal integer to an int, transfer a string that returns a decimal integer: to the int() function.

no_of_day = "23" days
no_of_day_int = int(no_of_day)
type(no_of_day_int)
<type 'int' >

The total operation will be done successfully if you try to do the math now:

print(no_of_day_int+5)
28

Remember, the commas you need to delete before passing the number to the int() function if the number contains commas, marking off thousands, millions, etc.:

total = "1,000,000"int(total.replace(",", ""))
1000000

When you execute the conversion between string to an integer, just make sure that you are using a correct base representing integers in various number systems. The number 54731 is expressed as D5CE in the hexadecimal method, for instance. You need to use Base 16 to convert it to a decimal integer:
If you move the D5CE String without setting the base to the int() function, the ValueError exception will be:

int ("D5CE", 16)
54731
Traceback (last call last):
'' file, line 1, in
ValueError: invalid literal with base 10 for int(): 'D5CF'

Conclusion:
In Python, using the int() function, you can convert a string to an integer.

How to Check whether a Directory or File Exists in Bash

Numerous scenarios will arise where you may need to perform an action based on whether a file exists or not.

While using the test command in Bash, you should determine whether a file exists and determine its file type.

A test command can take one of three possible syntax:

Test expression.

[ EXPRESSION ]

[[ EXPRESSION ]]

If you want a script to be portable, you should use the available command on all POSIX shells. The latest version of the test command, [[ (double brackets), is supported on most modern systems using the Bash, Zsh, and Ksh as a default shell.

Check if the file exists.

When checking a specific file, the most commonly used FILE operations include -e and -f. The first one will verify any file’s existence regardless of what type of file it is, while the second one will only return true for those files that are regular files (not a directory or a device).

The most efficient method of determining whether a file exists uses the test command and the if statement. Suppose you see any of the following, the /etc/resolv.conf file exists:

FILE=/etc/resolv.conf

if test -f "$FILE"; then

echo "$FILE exists."

fi
FILE=/etc/resolv.conf

if [ -f "$FILE" ]; then

echo "$FILE exists."

fi
FILE=/etc/resolv.conf

if [[ -f "$FILE" ]]; then

echo "$FILE exists."

fi

If you want to deliver a different action based on whether the file exists or not, simply use the if/then construct:

FILE=/etc/resolv.conf.

if [ "$FILE" ]; then

echo "$FILE exists."

else.

echo "$FILE does not exist."

fi

You can also operate a printer without the need for an if statement. The command following the && operator is only executed if the test command’s exit code is valid.

test -f /etc/resolv.conf && echo "$FILE exists."
[ -f /etc/resolv.conf ] && echo "$FILE exists."
[[ -f /etc/resolv.conf ]] && echo "$FILE exists."

When performing a series of commands using the && operator, make sure the semicolon does not separate them.

[ -f /etc/resolv.conf ] && { echo "$FILE exist."; cp "$FILE" /tmp/; }

What is said after the || operator is only valid as long as the test command’s exit status is false.

[ -f /etc/resolv.conf ] && echo "$FILE exist." || echo "$FILE does not exist."

Verify that Directory Exists.

The -d test tools you to quickly determine whether a file is a directory.

To check whether Docker’s /etc. The directory is present, use:

FILE=/etc/docker

if [ -d "$FILE" ]; then

echo "$FILE is a directory."

fi

[ -d /etc/docker ] && echo "$FILE is a directory."

Also, you can use the double brackets [[ instead of the single brackets [.

Check if the file already exists.

Moreover, the test expression can be negated using the word not. ! logical not operator:

FILE=/etc/docker

if not ( -f "$FILE" ]; then

echo "$FILE does not exist."

fi

Similar to above:

[ ! -f /etc/docker ] && echo "$FILE does not exist."

Check for multiple files.

Instead of using complex nested if/else statements, you can write a little more simply by using logic like this:

if [ -f /etc/resolv.conf -a -f /etc/hosts ]; then
echo "Both files exist."

fi

if [[ -f /etc/resolv.conf && -f /etc/hosts ]]; then

echo "Both files exist."

fi

Without using the IF statement:

[ -f /etc/resolv.conf -a -f /etc/hosts ] && echo "Both files exist."

[[ -f /etc/resolv.conf && -f /etc/hosts ]] && echo "Both files exist."

File test operators.

The test command includes some of the following file operators, which indicate whether a file is of a particular type.

  • -b FILE - True if that FILE exists and is also a special block file.
  • -c FILE - True if that FILE exists and is also a special character file.
  • -d source - True if source exists and is also a directory.
  • -e FILE - True if that FILE exists and is also a file, regardless of the type of (node, socket, directory, etc.).
  • -f FILE - True if that FILE exists and is also a regular file (not a device or directory).
  • -G FILE - True if that FILE exists and has the same group as the user is running that command.
  • -h FILE - True if that FILE exists and is also a symbolic link.
  • -g FILE - True if that FILE exists and also has set-group-id (sgid) flag set.
  • -k FILE – True if that FILE exists and also has a sticky bit flag set.
  • -L FILE – True if that FILE exists and is also a symbolic link.
  • -O FILE – True if that FILE exists and is also owned by the user running a command.
  • -p FILE – True if that FILE exists and is also a pipe.
  • -r FILE – True if that FILE exists and is also readable.
  • -S FILE – True if that FILE is also a socket.
  • -s FILE – True if that FILE exists and also has nonzero size.
  • -u FILE – True if that FILE exists, and also set-user-id (suid) flag is set.
  • -w FILE – True if that FILE exists and is also writable.
  • -x FILE – True if that FILE exists and is also executable.

How to Check Python Version

Python is one of the most successful programming languages in the world. It is used to develop websites, write scripts, machine learning, analyze data, and many more.

This article explains how to check what Python version is installed on your operating system working the command line. This can be beneficial when installing applications that require a particular version of python.

We will also explain to you how to programmatically determine what Python version is installed on the system where the Python script is running. For example, when writing Python scripts, you will require determining whether the script supports python’s version on the user’s machine.

Python Versioning

Python uses semantic versioning. Production-ready releases are versioned in the following scheme:

MAJOR.MINOR.MICRO

For example, in Python 3.6.8, 3 is a major version, 6 is a minor version, and 8 is a micro version.

  •  MAJOR – a python, has two major versions that are not fully cooperative: Python 2 and Python 3. For example, 3.5.7, 3.7.2, and 3.8.0 are all part of the Python 3 major version.
  • Minor: These announcements are bringing new features and roles. For example, 3.6.6, 3.6.7, and 3.6.8 are all part of the Python 3.6 minor version.
  • Micro: The new micro versions include various bug fixes and enhancements.

Development announcements have additional qualifiers. For more information, read the Python “Development Cycle” documentation.

Checking Python Version

Python is pre-installed on most maximum Linux distributions and macOS. On Windows, you have to download and install it if you want.

To get which version of python is fixed on your system, run the Python –version or Python -V command:

$ python --version

The order will print the default Python version, in this case, that is 2.5.15. The version installed on your system maybe another.

Output:

Python 2.7.15+

The default version of python will be applied by all scripts that have /usr/bin/python set as an interpreter in the script’s shebang line.

Some Linux distributions have various versions of python installed at the same time. The Python 3 binary is frequently named python3, and the Python 2 binary is called python or python2, but that may not always be the case.

You can check if you have Python 3 installed by typing:

$ python3 --version
Output:

Python 3.6.8

Python 2 support ended in 2020. Python 3 is the today and future of the programming language.

At the time of writing this article, the newest major release of python is version 3.8.x. The possibilities are that you can own an older version of Python 3 installed on your system.

If you want to install the most advanced python version, the method depends on your running system.

Programmatically Checking Python Version

Python 2 and Python 3 are different. The code written in Python 2.x may not work in Python 3.x, so you have to write two other codes.

The sys module that is open in all Python versions gives system-specific parameters and functions. sys.version_info enables you to discover the Python version installed on the system. It reflects a tuple that contains the five version numbers: major, minor, micro, release level, and serial.

Let’ say you have a script that needs at least Python version 3.5, and you want to tell whether the system meets requirements. You can do that by merely monitoring the major and minor versions:

import sys

if not (sys.version_info.major == 3 and sys.version_info.minor >= 5):

   print("This script requires Python 3.5 or higher!")

   print("You are using Python {}.{}.".format(sys.version_info.major, sys.version_info.minor))

   sys.exit(1)

If you run the script using Python version less than 3.5, it will produce the following output:

Output:

Python 3.5 or higher is required to run this script. 

You are using Python 2.5.

To write Python code that runs below both Python 3 and 2, use the future module. It enables you to run Python 3.x-compatible code below Python 2.

Conclusion: 

Using the python --version, it is very easy to find what version of python is installed on your system.

How to Change user password in Linux

This write-up is being provided to guide you through the procedure of changing your own user password in the application named Linux.

One interesting thing is that you can even forcefully make users change the password used for a login in Linux and that will be discussed here.

The procedural steps that are being provided here in this guide can also be used in other applications like Ubuntu, Debian, and CentOS.

Putting in the required changes in your already existing Password

If you wish to change the login details specifically the user password for your user login you will have to provide the command mentioned below with no other tit- bits following,

 $ passwd

Changing password for linuxize.

(Current) UNIX password:

Enter new UNIX password:

Retype new UNIX password:

passwd: password updated successfully

Once you put in the command $ password, a screen with the text mentioned above will pop up asking you the below-mentioned questions,

  • What is your current password?
  • What is the new password? Entering new password
  • Mention the new password again

Following the procedure above you will be easily able to bring the required changes in your user password.

Always remember that while filling the answers to the above questions you will not find them being showcased on the screen and front and that is totally normal.

Finally, when you try logging in to your system you will find that your new password has been generated and you can login using the freshly brewed user password.

How to facilitate change in password of another user?

It is not a factor to be surprised with as it has been already acquainted with you that access is granted to only the user who is rooted to the account or a user who has a sudo connection to the account will be provided the required privilege for making changes in the refreshed password for the account. The process that will be mentioned below is being mentioned keeping in mind that you are someone with the privilege of being connected to the account being handled as a sudo user.

When you are designing a change in a password for a different account you will have to type in the password command and entailing it should be the username of the account needing password changes. If we consider a password change in the account named lineux then the command followed will be,

$ sudo password lineux

Next step will be you coaxed into filling in a new password and confirming it:

Output

Enter new UNIX password:

Retype new UNIX password:

Once you are at the end of the procedure you will be faced with a command exactly like below,

Output

$ Password: password updated successfully

How can a user be pressured to change password at next login?

It has been set by default in many applications that the password set by a user for login details does not ever expire. Now a user can be pressurized to change the password when logging in for another time by undergoing a few commands while on the portal for Linux. The command that is provided for expiration of the old password is entailed by the name of the user:

$ sudo password --expire linuxize

Once you squeeze in the command mentioned above you will find the already existing password turning out to be immediately expired.

This procedure of immediate expiration of user’s earlier or old password will put pressure on the user to finally have the user password changed because of a message that will pop up when they log in again:

$ ssh linuxize@192.168.121.209
OUTPUT

WARNING: Your password has expired.

You must change your password now and login again!

Changing password for linuxize.

(Current) UNIX password:

Enter new UNIX password:

Retype new UNIX password:

password: password updated successfully

Connection to 192.168.121.209 closed.

You will see the connection being closed once the newly made and refreshed password is set by the user.

Conclusion

The write-up that was provided above was to help people with being able to bring out the required changes in their user password in a specific application named Linux.

The guidance that you got in the above right upper was how can you bring out the specific changes in the password and how can someone set an expiry limit to their password.

How to Add and Remove Users on Ubuntu 20.04

When provisioning a new Ubuntu system, the main task to be done is adding and removing users. Each user can have various permission levels and specific settings for different command-line and GUI applications.

So in this article, we have explained how to add and remove user accounts on Ubuntu 20.04

Before we start

Let us see some points.

Only root or users with sudo rights can create and remove users.

The following two ways are used to create new users:

  1. From the command line.
  2. Through the GUI.

Adding a User from the Command Line

In Ubuntu, there are a couple of command-line tools that you can do to create a new user account that is useradd and adduser.

useradd is a low-level utility. adduser is a script written in Perl that works as a friendly interactive frontend for useradd.

It is swift and easy to add a new user. Entreat the adduser command accompanied by the username. For example, to produce a new user account named username, you would work on the subsequent command

$ sudo adduser username
Output

Adding user `username '...

Adding new group `username' (1001) ...

Adding new user `username' (1001) with group `username' ...

Creating home directory `/home/username' ...

Copying files from `/etc/skel' ...

You will be examined a series of problems. Enter and validate the new user password. Answering all other questions is voluntary.

Output: 

Enter new UNIX password: 

Retype new UNIX password: 

passwd: password updated successfully

Changing the user information for username

Enter the new value, or press ENTER for the default

Full Name []: 

Room Number []: 

Work Phone []: 

Home Phone []: 

Other []: 

Is the information correct? [Y/n]

In the end, you will be required to confirm that the information you typed is accurate or not

The command will generate the new user’s home directory and copy files from /etc/skel to it. Inside the home directory, the user can write, edit, and delete files and directories which they want.

If you need the new user to be capable of performing administrative tasks, you require to add the user to the sudo group :

$ sudo usermod -aG sudo username

Adding a User through the GUI

If you are not satisfied with the command line, you can add a new user account through the GUI also. To do so, you will need to follow the steps given below:

  1. The first step is to open the settings window and click on the “Users” tab.
  2. Then you will need to click on the “Unlock” button and open your user password when mentioned.
  3. After you enter the password, the “Unlock” button will convert to a green “Add User” button.
  4. Then you will need to click on the “Add User” button, and then Add user dialog will arrive:
  5. Then you will need to select whether the new user should be a standard or administrator user and insert information. Once done, then you will need to click on the “Add” button.

Removing a User from the Command Line

The following two commands are used in Ubuntu to delete a user account: userdel and its interactive frontend deluser.

To delete the user, request the deluser command and pass the username as the argument:

$ sudo deluser username

The above command will not remove the user files.

If you need to delete the user and its home directory and mail spool, use the –remove-home flag command for a better result.

 Removing a User through the GUI

  1. The first step is to open the settings window and click on the “Users” tab.
  2. Then click on the “Unlock” button, and insert your user password when mentioned.
  3. Then click on the username which you want to delete, and you will observe a red “Remove User..” button on the base right corner, which indicated that the user could be removed.
  4. Then click the “Remove User..” button, and you will be mentioned whether to keep or delete the user home directory. By clicking on one of those buttons removes the user that you are willing to do.

Conclusion:

In this article, you have determined how to add and remove users in Ubuntu 20.04. Understanding how to add and remove users is one of the essential skills a Linux user should know.

How to show a list of all databases in MySQL

When we work with a MySQL server, it is an everyday activity to view or list the databases, display the database table. The display of the user account information and privileges residing on the server.

Displaying MySQL Databases:

Open the MySQL Command Line Client that appears with a prompt for mysql>. First, use the password you created during the installation of MySQL to log into the MySQL database server. You are now linked to the host of the MySQL server, where all SQL statements can be executed. Finally, to list/show databases, run the SHOW Databases command.

The most popular way to get a list of MySQL databases is to connect to a MySQL server using the MySQL client and execute the Display DATABASES order.

Open the MySQL server using the following command and, when prompted, enter your MySQL user password:

mysql -u user -p

Utilizing schemas:

MySQL also allows one to list databases with another instruction, which is a Display SCHEMAS statement. This command is a Display DATABASES synonym and gives the same result.

SCHEMAS SHOW;

Displaying all MySQL databases:

You would need to log in as a user who can access all the databases to list all the databases on the MySQL server by default. The MySQL root user, or set a global privilege for Display DATABASES.

Log in to the root MySQL user:

mysql -u user -p

Run the DATABASES Display command:

DATABASES SHOW;

On the MySQL server, you can see a list of all the databases.

Database list using pattern matching:

The Display Databases command in MySQL also offers an alternative that allows us to filter the returned database by matching the LIKE and WHERE clauses with different patterns. The LIKE clause lists the name of the database that fits the pattern specified. More versatility is provided by the WHERE clause to list the SQL statement database that fits the specified condition.

Syntax:

The syntax for using pattern matching with the Display Databases command is as follows:

LIKE pattern Display DATABASES;

DISPLAY DATABASES WHERE the phrase is;

You can understand this with the following example where the percentage sign assumes zero, one, or several characters:

LIKE " percent schema" Display DATABASES;

The LIKE clause is often not sufficient; we can then conduct a more detailed search to query the information schema’s database information from the schema table. In MySQL, the information schema is a database of information to get the results using the command Display DATABASES.

FROM information schema.schema; SELECT schema name

With the Display DATABASES instruction, you can check how the WHERE clause is used. This statement returns the database whose name for the schema begins with ‘s’::

SELECT schema name FROM schema. Schema details WHERE schema name LIKE percentage;

Database list via command line:

You can use either the MySQL command with the -e option that stands for executing or the mysqlshow that shows database and table information. It is used to get a list of databases without logging in to the MySQL shell.

This is particularly useful when you want to work with shell scripts for your MySQL databases.

To present a list of all databases, run the following command on your terminal:

mysql -u user -p -e 'database display;'

The Conclusion:

Here, you have learned how to display or list tables in the MySQL database and use pattern matching to filter performance.

How to Run Cron Jobs Every 5, 10, or 15 Minutes

A cron job is work performed at given intervals. A minute, hour, Day of the month, month, Day of the week, or any combination may be scheduled to perform the tasks.

In general, Cron jobs are used to automate system maintenance or management, such as backing up databases or records, updating the system with the latest security updates, checking the use of disk space, sending emails, etc.

Some of the most widely used cron schedules are running cron tasks. It executes in 5, 10, or 15 minutes intervals.

Syntax and Operators of Crontab

Crontab (Cron table) is a text file that specifies the cron work schedule. You can build, access, change and delete Crontab files with the crontab command.

each and every line holds six fields isolated by a space followed by the command to be executed:

* * * * * command(s)

^ ^ ^ ^ ^

| | | | |     allowed values

| | | | |     -------

| | | | ----- Day of week (0 - 7) (Sunday=0 or 7)

| | | ------- Month (1 - 12)

| | --------- Day of month (1 - 31)

| ----------- Hour (0 - 23)

------------- Minute (0 - 59)

It also accepts the following operators for the five fields at the beginning (time and date):

* – Asterisks as an operator means it allows all the values. If you have the asterisk symbol in the Minute sector, every Minute, the task is performed.

– – The hyphen operator allows several values to be defined. If you set 1-5 in the Day of the Week box, the task will run weekly (From Monday to Friday). The set is inclusive, which means that the range contains the first and last values.

, – The comma operator helps you to identify the repetition list of values. If you have 1,3,5in the Hour area, the task will run at 1 am, 3 am, and 5 am. The list can contain ranges and single values, 1-5,7,8,10-15

/ – You can use the slash operator to define phase values that can be used in combination with ranges. For, e.g., if you have 1-10/2 in the Minute’s sector, this means that the action is executed in the range 1-10 every two minutes, the same as specifying 1,3,5,7,9. Also, you can use the asterisk operator instead of a set of values. “You can use “*/20” to designate a job to be executed every 20 minutes.

The system-wide crontab file syntax varies slightly from that of user crontabs. This requires an additional mandatory user area defining which user is running the cron job.

* * * * * <username> instruction <username> (s)

Use the crontab -e command to modify the crontab file or build one if it doesn’t exist.

Run a job every 5 minutes with Cron

Every five minutes, there are two ways to run a cron job.

The first choice is to create a list of minutes using the comma operator:

0,5,10,15,20,25,30,35,40,45,50,55 * * * *Command

The above line is syntactically right, and it’s only going to work correctly. Typing the entire list might, however, be tedious and prone to mistakes.

The second choice for specifying a job to be done every 5 minutes is to use the phase operator:

*/5 * * * * Order * Command *

*/5 means that you create a list of all minutes and run the job from the list for every fifth value.

Run a job every 10 minutes with Cron

To run a cron job every 10 minutes, in the crontab code, add the following line:

*/10 * * * * command

Run a job with Cron every 15 minutes

To run a cron job every 15 minutes, in the crontab code, add the following line:

*/15 * * * * command

How to Rename Files and Directories in Linux

Renaming documents is one of the most common tasks you regularly want to carry out on a Linux system. You can rename documents by use of a GUI document manager or through the command-line terminal.

Renaming a single document is not hard however renaming more than one document at once may be a challenge, especially for customers who’re new to Linux.

In this tutorial, we will display you the way to use the mv and rename instructions to rename documents and directories.

Renaming Files with the mv Command

The mv command (short of circulate) is used to rename or circulate documents from one region to another.

Syntax used for the mv command is as follows:

mv [OPTIONS] source destination

Copy

The source may be one or more documents, or directories and destination may be a single document or directory.

If you specify more than one document as source, the destination should be a directory. In such cases, the source documents are transferred to the targeted directory.

If you specify a single document as source, and the destination target is a current directory, then the document is moved to the required directory.

To rename a document, you want to specify a single document as a source and a single document as a destination target.

For instance, to rename the document file1.txt as file2.txt you’ll run:

mv file1.txt file2.txt

Renaming more than one documents with the mv Command

The mv command can rename only one command at a time effectively  , however it may be used together with different commands which include find or inside bash for or while loops to rename more than one document.

The following instance indicates the way to use the Bash for loop to rename all .html documents in the present directory by converting the .html extension to .php.

for f in *.html; do

    mv -- "$f" "$f%.html">.php"

done

Copy

Let’s examine the code line by line:

The first line creates a for loop and iterates through a listing of all documents edging with .html.

The 2d line applies to every object of the listing and moves the document to a new one replacing .html with .php.

The element ${document%.html} is by use of the shell parameter expansion to get rid of the .html element from the filename.

done suggests the end of the loop segment.

Here is an example by use of mv in combination with find to gain similar above:

find . -depth -name "*.html" -exec sh -c 'f=""; mv -- "$f" "$.php"' ;

" xss="removed">Copy

The find command is passing all documents ending with .html in the present directory to mv one at a time using the -exec option. The string is the name of the document presently being processed.

As you could see from the examples above, renaming more than one document using the mv command isn’t an easy project because it requires a great amount of Bash scripting.

Renaming Files with the rename Command

The rename command is used to rename more than one document. This command is extra advanced than mv because it requires a few fundamental understanding of regular expressions. There are  variations of the rename command with unique syntax.

Here in this tutorial, we are going to use  the Perl version of the rename command. If you don’t have this version set up on your system, you could effortlessly install it by using the package manager of your distribution.

Install rename on Ubuntu and Debian

sudo apt install rename

Install rename on CentOS and Fedora

sudo yum install prename

Install rename on Arch Linux

yay perl-rename ## or yaourt -S perl-rename

The syntax for the rename command is as follows:

rename [OPTIONS] perlexpr documents

Copy

The rename command will rename the documents in step with the required perlexpr regular expression. You can study more about perl regular expressions here .

The following instance will change all documents with the extension .html to .php:

rename 's/.html/.php/' *.html

You can use the -n choice to print names of documents to be renamed, without renaming them.

rename -n 's/.html/.php/' *.html

The output will look something like this:

rename(file-90.html, file-90.php)

rename(file-91.html, file-91.php)

rename(file-92.html, file-92.php)

rename(file-93.html, file-93.php)

rename(file-94.html, file-94.php)

By default, the rename command doesn’t overwrite present documents. Pass the -f choice to permit present documents to be overwritten:

rename -f 's/.html/.php/' *.html

Below are some more common examples of how to use the rename command:

Replace areas in filenames with underscores

rename 'y/ /_/' *

Convert filenames to lowercase

rename 'y/A-Z/a-z/' *

Convert filenames to uppercase

rename 'y/a-z/A-Z/' *

Conclusion

Here we have shown you the way to use the mv and rename instructions to rename documents.

There also are different instructions to rename documents in Linux, which include mmv. New Linux customers who’re intimidated by the command line can use GUI batch rename equipment which include the Métamorphose .

If you’ve got any questions or feedback, Just feel free to leave a comment.

How to Rename Directories in Linux

Renaming directories is one of the most primary operations you frequently want to perform on a Linux system. You can rename directories from the GUI document manager with more than one click or the use of the command-line terminal.

This article explains a way to rename directories by the use of the command-line.

Renaming Directories

In Linux and Unix-like running systems, you may use the mv (short of move) command to rename or circulate documents and directories from one place to any other.

The syntax of the mv command for shifting directories is as follows:

mv [OPTIONS] source destination

For instance, to rename the listing dir1as dir2 you will run:

mv dir1 dir2

When renaming directories, you need to specify precisely arguments to the mv command. The first argument is the present name of the directory, and the second argument is the new name.

It is essential to notice that if dir2 already exists, dir1 is moved to the dir2 directory.

To rename a listing that isn’t in the present  running directory, you want to specify both absolutely the or relative path:

mv /home/user/dir1 /home/user/dir2

Renaming Multiple Directories

It is easy  to rename a single directory challenge, however renaming more than one directories straight away may be a challenge, specifically for new Linux users.

Renaming more than one directories straight away is not often needed.

Renaming Multiple Directories with mv

The mv command can rename the handiest one report at a time. However, it may be used along with different instructions such as find or interior loops to rename more than one document straight away.

Here is an example displaying a way to use the Bash for loop to append the present date to the names of all directories in the present operating directory:

for d in *; do

  if [ -d "$d" ]; then

    mv -- "$d" "$d">_$(date +%Y%m%d)"

  fi

done

Let’s examine the code line through line:

  • The first line creates a loop and iterates by a listing of all documents.
  • The 2nd line examines if the document is a directory.
  • The 3rd line appends the present date to every directory.

Here is an answer to the same challenge the usage of mv in aggregate with find:

find . -mindepth 1 -prune -type d -exec sh -c 'd=""; mv -- "$d" "$_$(date +%Y%m%d)"' ;

The find command is passing all directories to mv one after the other the use of the -exec alternative. The string  is the name of the listing presently being processed.

As you may see from the examples, renaming more than one directories with mv isn’t an easy challenge because it requires a very good understanding of Bash scripting.

Renaming more than one directories with rename

The rename command is used to rename more than one document and directories. This command is superior to mv because it calls for a fundamental understanding of regular expressions.

There are  variations of the rename command with unique syntax. We use the Perl version of the rename command. The documents are renamed in step with the given perl ordinary expression .

The following instance suggests a way to update areas in the names of all directories in the present  operating listing with underscores:

find . -mindepth 1 -prune -type d | rename 'y/ /_/'

To be on the safe side, pass the -n alternative to rename to print names of the directories to be renamed without renaming them.

Here is any other instance displaying a way to convert listing names to lowercase:

find . -mindepth 1 -prune -type d | rename 'y/A-Z/a-z/'

Conclusion

We’ve proven you a way to use the mv instructions to rename directories.

If you’ve got  any questions or feedback, just  leave a comment.