Linux Find String in Folder

Linux Find String in Folder

In our examples, we assume, that we want to find the name of the network card “eno16777728” in /etc folder recursively.

This example search “eno16777728” in /etc folder (-r means recursive, -n means print line number):

grep -nr "eno16777728" /etc

In next example, we would like to add ignore case with “i” option:

grep -inr "eno16777728" /etc

If you are not super user, it is good idea to suppress error messages with “s” option:

grep -insr "eno16777728" /etc

In examples mentioned before, searched string could be also a part some string. In next example, we would like to find “eno16777728” as whole word only (w option):

grep -winsr "eno16777728" /etc

The alternative way is use find and exec option:

find /etc -type f -exec grep -il 'eno16777728' {} \;

In this case option exec executes grep command for each founded file. In {} is a list of founded files.

Linux How to Remove Directory

Linux How to Remove Directory

To remove an empty directory use the command:

rmdir directory/

To remove a directory which contains files or sub-directories use this way:

rm -r not-emty-directory/

If you want to ignore nonexistent files and never prompt, use the option “f”:

rm -rf not-empty-directory/

Command rm has option “v” which explains what is being done.

rm -rv directory

If you don’t have permision to delete folder add sudo at the beginning:

sudo rm -rv directory

If you are not 100 % sure if you won’t remove all the files in directory, use -i option:

rm -rvi directory

Shell will ask you before removing each file.

Linux How to Find File by Name

Linux How to Find File by Name

To search for files on the disk, you can use the find command. The find command has the following syntax:

find /where_to_start -name "name_of_file"

If you do not mention the parameter /where_to_start, it will automatically search in the current directory. The current directory, which you currently stand, is available by typing pwd command. The second parameter -name “name_of_file” – is shown filter. This filter shows only those files in which there is a string “name_of_file”. You can also include an asterisk, for example: “name_of_file.*”.

If you want to recursively overview /etc directory and find all files that have the extension “.conf”, you can do it this way:

find /etc -name "*.conf"

If the find command does not access to any folder, it write error about it. If you do not run the command as super user, it is better to redirect error messages to $HOME/find_errors or to trash /dev/null.

In next example we redirect errors to file find_errors that will be situated in our home folder:

find /etc -name "*.conf" 2> $HOME/find_errors

In next example we redirect errors to the system trash:

find /etc -name "*.conf" 2> /dev/null

To find file by a name, ignoring the case use option -iname:

find /etc -iname "name_of_file"

If you want to find all files these don’t match the pattern:

find /etc -not -name ".*.conf"

JOE Tutorial for Linux

JOE Tutorial for Linux

Start joe:

joe ./textFile.txt

Show help:

Ctrl + K + H (to hide help, enter this command again)

Save file

Ctrl + K + D

Save and exit:

Ctrl + K + X

Exit without saving:

Ctrl + K + Q

Go to previous/next screen:

Ctrl + U/Ctrl + V

Move cursor to the start/end of file file:

Ctrl + K + U/Ctrl + K + V

UnDo recent change:

Ctrl + Shift + _

ReDo undone change:

Ctrl + Shift + ^

Insert or overwrite:

Ctrl + T

Selecting text:

Ctrl + K + B (block begin)
Ctrl + K + K (block end)

When you have block selected, to move block using:

Ctrl + K + M

Delete block:

Ctrl + K + Y

Copy block:

Ctrl + K + C

Search in the file:

Ctrl + K + F

Then choose between ignore (I), replace (R) options. To navigate to next result use:

Ctrl + L

If you want to change joe’s default setting use:

Ctrl + T

You can turn on/off auto-indent, word wrap, line numbers, highlighting and set tab width, left margin, etc.

Linux How to Change Password

Linux How to Change Password

If you want to change password of user that are currently logged in, just type:

passwd

Input old password, then type new password 2 times.

Did you run the passwd command as root? There is a difference between whether you change the password as an root or as a standard user. While the root is called upon to enter a password, the password policy more fully. But if he fails, the password is changed, even though the system grumble. Current user must comply with password policy.

Let’s assume, that you are user bob. If you would like to change bob’s password, log as bob and type:

passwd

If you are root, and if you want to change bob’s password, type:

passwd bob

Please, always try to check, if you set good new password. There is a possibility, that you misspell the password, so try to log in to second console (or putty session) immediately after login.

You can also set the following options:

Option Property
-d Delete password for an account. It will set a passwordless account.
-e Expire. The user will be forced to change the password in the next login.
-n Minimum password lifetime.
-x Maximum password lifetime.

 

Generate SSL certificates using openssl

Generate SSL certificates using openssl with a Certificate Signing Request and signing it by a Certificate Authority.

The file ca.key and ca.crt are the Certificate Authority

We will be genrating the .key and .csr (Certificate Signing Request) files from the below command.

[root@node01 ssl]# openssl req -new -sha256 -newkey rsa:2048 -nodes -keyout linuxcent.com.key -days 365 -out linuxcent.com.csr -sha256 -subj "/C=IN/ST=TG/L=My Location/O=Company Ltd./OU=IT/CN=linuxcent.com/subjectAltName=DNS.1=linuxcent.com"

Verify the .csr file that is generated as shown below:

[root@node01 ssl]# openssl req -in linuxcent.com.csr -noout -text
Certificate Request:
Data:
Version: 0 (0x0)
Subject: C=IN, ST=TG, L=MY Location, O=Company Ltd., OU=IT, CN=linuxcent.com/subjectAltName=DNS.1=linuxcent.com
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (2048 bit)
Modulus:00:e4:b4:24:d7:22:ec:5d:c1:37:8c:d1:a0:62:17:
96:24:77:8d:75:4e:d5:74:15:4d:61:e0:8b:66:d6:
                Exponent: 65537 (0x10001)
        Attributes:
            a0:00
    Signature Algorithm: sha256WithRSAEncryption
         87:ef:83:b2:a6:f5:3a:f3:6f:1c:e4:02:ec:bf:5d:75:64:1d:
-- OUTPUT TRUNCATED --

Now we will using the root ca.key and ca.crt to digitally sign this .csr and generate a .crt

[root@node01 ssl]# openssl x509 -req -in linuxcent.com.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out linuxcent.com.crt -days 365 -sha256
Signature ok
subject=/C=IN/ST=TG/L=My Location/O=Company Ltd./OU=IT/CN=linuxcent.com/subjectAltName=DNS.1=linuxcent.com

We have generated the .crt file from the .csr

[root@node01 ssl]# ls linuxcent.com.crt linuxcent.com.key 
linuxcent.com.crt linuxcent.com.key

Therefore we have successfully generated the linuxcent.com.key file and linuxcent.com.crt, and digitally self signed with the root CA key and certificates.

Generating Self Signed SSL certificates using openssl

The x509 is the certificate signing utility we will be using here.

We generate the ssl self signed certificate using the following command, request as demonstrated below.

openssl req -x509 -days 365 -sha1 -newkey rsa:2048 -nodes -keyout linuxcent.com.key -out linuxcent.com.crt -sha256 -subj "/C=IN/ST=State/L=My Location/O=Company Ltd./OU=IT/CN=linuxcent.com/subjectAltName=DNS.1=linuxcent.com"

The Days parameter can be specified to any number of days depending on your requirement.

The Self signed certificates are mostly commonly used within the internal network or among small group of familiar individuals like an office for specific purposes and not advised to be used out in the public domain as the browser does not identify the certificate authenticity or the ingenuity of the concerned website. The Self-signed certificates are not validated with any third party until and unless you import them to the browsers previously.

BASH “switch case” in Linux with practical example

The switch case in BASH is more relevant and is widely used among the Linux admins/Devops folks to leverage the power of control flow in shell scripts.

As we have seen the if..elif..else..fi Control Structure: Bash If then Else. The switch case has a stronger case where it really simplifies out the control flow by running the specific block of bash code based on the user selection or the input parameters.

Let’s take a look at the simple Switch case as follows:

OPTION=$1
case $OPTION in
choice1)
Choice1 Statements
;;

choice2)
Choice2 Statements
;;

choiceN)
ChoiceN Statements
;;

*)
echo “User Selected Choice not present”
exit 1

esac

The OPTION is generally read from user input and upon this the specific choice case block is invoked.

Explanation:
In the switch command the control flow is forwarded to case keyword and stops here, it checks for the suitable match to pass over the control to relevant OPTION/CHOICE statement block. Upon the execution of the relevant CHOICE statements the case is exited once the control flow encounters esac keyword at the end.

Using the Pattern match
The control flow in bash identifies the case options and proceeds accordingly.
There can be cases where you can match the Here you might have observed that the user input the regular expression and the logical operators using the | for the input case

#! /bin/bash

echo -en "Enter your logins\nUsername: "
read user_name 
echo -en "Password: "
read user_pass 
while [ -n $user_name -a -n $user_pass ]
do

case $user_name in
    ro*|admin)
        if [ "$user_pass" = "Root" ];
        then
            echo -e "Authentication succeeded \ n You Own this Machine"
	    break
        else
            echo -e "Authentication failure"
            exit
        fi
    ;;
    jenk*)
	if [ "$user_pass" = "Jenkins" ];
	then
		echo "Your home directory is /var/lib/jenkins"
	    	break
	else
        	echo -e "Authentication failure"
	fi
        break
    ;;
    *)
        echo -e "An unexpected error has occurred."
        exit
    ;;
esac

done

You should kindly note that the regex used for the cases at ro*|admin and jenk*

We now have demonstrated by entering the username as jenkins and this will get matched with the jenkins case the control flow successfully enters into relevant block of code, checking the password match or not is not relevant for us as we are only concerned till the case choice selection.
We have named the switch case into a script switch-case.sh and run it, Here are the results.

OUTPUT :

[vamshi@node02 switch-case]$ sh switch-case.sh
Enter your logins
Username: jenkins
Password: Jenkins
Your home directory is /var/lib/jenkins

We have entered the correct password and successfully runs the jenkins case block statements

We shall also see the or ro*|admin case, demonstrated as follows.

[vamshi@node02 switch-case]$ sh switch-case.sh 
Enter your logins
Username: root
Password: Root
Authentication succeeded \ n You Own this Machine

We now test the admin username and see the results.

[vamshi@node02 switch-case]$ sh switch-case.sh 
Enter your logins
Username: admin
Password: Root
Authentication succeeded \ n You Own this Machine

Here is a more advanced script used to deploy a python application using the switch case..
Please refer to the Command line arguments section for user input

A complete functional Bash switch case can be seen at https://github.com/rrskris/python-deployment-script/blob/master/deploy-python.sh

Please feel free to share your experiences in comments.

Control Structure: Bash If then Else

The Bash being a scripting language does tend offer the conditional if else, We shall look at them in the following sections.

Firstly there needs to be a conditional check that has to be performed in order for the corresponding Block of code to be executed.

To break down the semantics of conditional control structures in BASH we need to understand The conditional keyword that performs the validation, the It is represented most commonly as “[“ and very rarely represented as “test” keyword.

It can be better understood by the following demonstration:

vamshi@linux-pc:~/Linux> [ 1 -gt 2 ]
vamshi@linux-pc:~/Linux> echo $?
1
vamshi@linux-pc:~/Linux>
vamshi@linux-pc:~/Linux> [ 1 -lt 2 ]
vamshi@linux-pc:~/Linux> echo $?
0

The [ is synonymous to the command test on the linux kernel.

vamshi.santhapuri@linux-pc:~/Linux> test 1 -gt 2

vamshi.santhapuri@linux-pc:~/Linux> echo $?
1
vamshi.santhapuri@linux-pc:~/Linux> test 1 -lt 2
vamshi.santhapuri@linux-pc:~/Linux> echo $?
0

We Shall now look at the different variations of Conditional controls structures.

  1. if then..fi

    if [ Condition ] ; then
    
    statement1...statementN
    
    fi
  2. if then..else..fi

    if [ Condition ] ; then
    
        If Block statements
    
    ...
    
    else
        else-Block statement
    
    fi
  3. if..then..elif then..elifN then..fi

    if [ Condition ] ; then
    
        If Block statement1
    
    ...
    
    elif [ elif Condition ]; then   # 1st elif Condition
    
        elif Block statement1
    
    
    elif [ elif Condition ]; then    # 2nd elif Condition
    
        elif Block statements
    
    elif [ elif Condition ]; then    # nth elif Condition
    
        elif Block statements
    
    fi

    An else can also be appended accordingly when all the if and elif conditions fail, which we will see in this section .

     

  4. if..then..elif then..elifN then..else..fi

    The “if elif elif else fi” control structure is like multiple test checking control diversion strategy in bash, gives the user the power to write as many test conditions as possible until a test condition is matched leading in the resultant block of code being executed. Writing this multiple elif can be tedious task and the switch case is mostly preferred

    if [ Condition ] ; then
    
        If Block statement
    
    elif [ elif Condition ]; then   # 1st elif Condition
    
        elif Block statement1
    
    elif [ elif Condition ]; then    # nth elif Condition
    
        elif Block statement
    
    ...
    
    else Block statementN # else block while gets control when none of if or elif are true.
    
        else Block statements
    
    fi

    Atleast one of the block statements are executed in this control flow similar to a switch case. The else block here takes the default case when none of the if nor the elif conditions matches up.

  5. Nested if then..fi Control structure Blocks

    Adding to the if..elif..else there is also the nested if block wherein the nested conditions are validated which can be Demonstrated as follows:

    if [ condition ]; then
    
        Main If Block Statements
    
        if [ condition ]; then # 1st inner if condition
    
            1st Inner If-Block statements
    
            if [ condition ]; then # 2nd inner if condition
    
                2nd Inner If-Block statements
              
                if [ condition ]; then 
                    Nth Inner If Block statements 
    
                fi
    
            fi
    
        fi
    
    fi

    This logic of nested ifs are used while dealing with scenarios where the outermost block of statements must be validated before, if the test succeeds then the control flow is passed to the innermost if test statement execution. Thus the name Nested if.

 

Here is the switch case bash script with practical explanation.
We will look at the Exit codes within the BASH in the next sections.

sed – The Stream editor in Linux

The Stream Editor(sed) is a text manipulation program, that takes the input from stdin and from the text files, It writes to the stdout and modifies the input files accordingly. The text manipulation means deleting characters and words; Inserting text into the source file on the fly.
This is a transformation operation and quiet a handy skill to have for someone working in linux shell.

The sed comprises of two operations, The first one is a regex search and match operation and the second one is replace operation accordingly. This combines the greater power of search and replace of text from stdin and from the flat files.
Here is general syntax of sed command is:

# sed [-n] -e 'options/commands' files
# sed [-n] -f sed-scriptfile
# sed -i filename -e 'options/commands'

-e is the edit option used on the cli.
-f to take the sed commands from the scriptfile
-n or –quiet option supresses the output unless specified with -p or -s

We will look at some of the notable options the sed offers.

Some practical usecases, But before that we take at our sample README.txt.

Substitute and Replace with sed:

sed command offers the -s option which is exclusive for search and replace operation also known as search and substitution.

[vamshi@node02 sed]$ echo Welcome to LinuxCent | sed -e 's/e/E/'
WElcome to LinuxCent

This replaces the e to E in the input received and prints to stdout.
We can apply the same to the Text file and achieve the same results.

[vamshi@node02 ~]$ sed -e 's|u|U|' README.txt
centos 	
debian 	
redhat 	
Ubuntu

But the important thins to be noted is that the first occurring pattern match per line is only replaced. In out case only 1 letter per line as the letter u is replaced in ubuntu by U.

Substitute and replace globally using the option -g.

We run the below command stdin input stream as show below:

[vamshi@node02 sed]$ echo Welcome to LinuxCent | sed -e 's/e/E/g'
WElcomE to LinuxCEnt

Running the global option g on the fileinput as shown below.

[vamshi@node02 ~]$ sed -e 's/u/U/g' README.txt
centos 
debian 	
redhat 	
UbUntU 	

Substitute the later occurrences using sed. We search for the 3rd occurrence of letter u and if matched replace it with U.

[vamshi@node02 ~]$ sed -e 's/u/U/3g' README.txt
centos 	
debian 	
redhat 	
ubuntU

In the above case we have seen the lowercase u has been replaced with Uppercase U at the third occurrence.
Now let us append the word to the end of the each line using the below syntax:

[vamshi@node02 ~]$ sed -e 's/$/ Linux/' README.txt
centos Linux
debian Linux
redhat Linux
ubuntu Linux

Adding text to the file data at the beginning of each line and writing to the stdout.

[vamshi@node02 Linux-blog]$ sed -e 's/^/Distro name: /' Distronames.txt 
Distro name: centos Linux
Distro name: debian Linux
Distro name: redhat Linux
Distro name: ubuntu Linux

sed Interactive Editor: How to write the modified sed data into the same text file?

We can use the -i Interactive Editor option in combination with most other sed options, the input file content is directly modified according to the command pattern.
Example Given.

[vamshi@node02 sed]$ sed -e 's/e/E/g' -i intro.txt
[vamshi@node02 sed]$ cat intro.txt
WElcomE to LinuxCEnt

We use the -i option to append some text to a file as demonstrated as follows:

[vamshi@node02 Linux-blog]$ sed -i 's/$/ Linux/' README.txt
[vamshi@node02 Linux-blog]$ cat README.txt 
centos Linux
debian Linux
redhat Linux
ubuntu Linux

Here we append the words Linux to end of the each line
Alternate to -i you can also use the output redirection to write to a new file  as shown below.

[vamshi@node02 ~]$ sed -e 's/$/ Linux/' README.txt > OSnames.txt

Delete Operations with sed

Delete all the lines containing the pattern:

[vamshi@node02 ~]$ sed -e /ubu/d README.txt
centos Linux 
debian Linux 
redhat Linux

Here we matched the word ubuntu and hence have deleted that line from output.

We can use the ! inverse operator with the delete, demonstrated as follows:

[vamshi@node02 Linux-blog]$ sed -e '/ubu/!d' Distronames.txt
ubuntu Linux

Using the Ranges in sed

Extracting only the specific /BEGIN and /END pattern using sed.

[vamshi@node02 Linux-blog]$ cat Distronames.txt | sed -n -e '/^centos/,/^debian/p'
centos Linux	
debian Linux

Substitution of Range of lines

[vamshi@node02 Linux-blog]$ sed -e  '1,3s/u/U/' Distronames.txt
centos LinUx.	
debian LinUx.	
redhat LinUx.	
ubuntu Linux.

Delete the . at the end of each line

[vamshi@node02 Linux-blog]$ sed -e 's/.$//' Distronames.txt

Print only the lines containing the word “hat”

[vamshi@node02 Linux-blog]$ sed -n -e '/hat/p' Distronames.txt 
redhat Linux

Use sed to Match the pattern insert text.
Insert the lines before the matched pattern in file

[vamshi@node02 Linux-blog]$ cat README.txt | sed -e '/centos/i\Distro Names '
Distro Names 
centos
debian
redhat
ubuntu

The above scenario we have inserted the sentence “Distro Names” before the occurrence of the work centos.

[vamshi@node02 Linux-blog]$ cat Distronames.txt | sed -e '1a\------------'
Distro Names 
------------
centos
debian
redhat
ubuntu

The ———— are appended to the text after the 1st line

Signals in Linux; trap command – practical example

The SIGNALS in linux

The signals are the response of the kernel to certain actions generated by the user / by a program or an application and the I/O devices.
The linux trap command gives us a best view to understand the SIGNALS and take advantage of it.
With trap command can be used to respond to certain conditions and invoke the various activities when a shell receives a signal.
The below are the various Signals in linux.

vamshi@linuxcent :~] trap -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP
6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1
11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM
16) SIGSTKFLT 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ
26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO 30) SIGPWR
31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3
38) SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13
48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12
53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7
58) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX

Lets take a look at some Important SIGNALS and their categorization of them:

Job control Signals: These Signals are used to control the Queuing the waiting process
(18) SIGCONT, (19) SIGSTOP , (20) SIGSTP

Termination Signals: These signals are used to interrupt or terminate a running process
(2) SIGINT , (3) SIGQUIT, (6) SIGABRT,  (9) SIGKILL,  (15) SIGTERM.

Async I/O Signals: These signals are generated when data is available on a Input/Output device or when the kernel services wishes to notify applications about resource availability.
(23) SIGURG,  (29) SIGIO,  (29) SIGPOLL.

Timer Signals: These signals are generated when application wishes to trigger timers alarms.
(14) SIGALRM,  (27) SIGPROF,  (26) SIGVTALRM.

Error reporting Signals: These signals occur when running process or an application code endsup into an exception or a fault.
(1) SIGHUP, (4) SIGILL, (5) SIGTRAP, (7) SIGBUS, (8) SIGFPE,  (13) SIGPIPE,  (11) SIGSEGV, (24) SIGXCPU.

Trap command Syntax:

trap [-] [[ARG] SIGNAL]

ARG is a command to be interpreted and executed when the shell receives the signal(s) SIGNAL.

If no arguments are supplied, trap prints the list of commands associated with each signal.
to unset the trap a – is to be used followed by the [ARG] SIGNAL] which we will demonstrate in the following section.

How to set a trap on linux through the command line?

[vamshi@linuxcent ~]$ trap 'echo -e "You Pressed Ctrl-C"' SIGINT

Now you have successfully setup a trap:>

When ever you press Ctrl-c on your keyboard, the message “You Pressed Ctrl-C” gets printed.

[vamshi@linuxcent ~]$ ^CYou Pressed Ctrl-C
[vamshi@linuxcent ~]$ ^CYou Pressed Ctrl-C
[vamshi@linuxcent ~]$ ^CYou Pressed Ctrl-C

Now type the trap command and you can see the currently set trap details.

[vamshi@node01 ~]$ trap
trap -- 'echo -e "You Pressed Ctrl-C"' SIGINT
trap -- '' SIGTSTP
trap -- '' SIGTTIN
trap -- '' SIGTTOU

To unset the trap all you need to do is to run the following command,

[vamshi@node01 ~]$ trap - 'echo -e "You Pressed Ctrl-C"' SIGINT

The same can be evident from the below output:

[vamshi@node01 ~]$ trap
trap -- '' SIGTSTP
trap -- '' SIGTTIN
trap -- '' SIGTTOU
[vamshi@node01 ~]$ ^C
[vamshi@node01 ~]$ ^C

 

Rename files in linux

The linux mv command has very featureset, It can be used to rename the file(s) and Directory names, also also used to relocate the contents and help better in organizing the files and directories on a linux OS.

Syntax of mv command:

$ mv [OPTIONS] </path/to/Source> </path/to/Destination>

How to rename a single file

The rename operation is linux is done using the mv command

[vamshi@linuxcent mv]$ ls
demo.txt
$ mv demo-today.txt demo-old.txt
[vamshi@linuxcent mv]$ ls
demo-old.txt

Here the file demo-today.txt has been renamed to demo-old.txt

How to move or relocate multiple files and directories at once into a Destination Directory

Out DemoProject Directory contains the following content

[vamshi@node02 DemoProject]$ ls
api LICENSE mvnw mvnw.cmd README.md

We are only interested to move out only selected directories core/ site/ admin/ and the file pom.xml to the target destination /tmp/Demo-test/, We can achieve this using the option -t --target-directory= Option

[vamshi@node02 DemoProject]$ mv -vi core/ site/ admin/ pom.xml -t /tmp/Demo-test/
‘core/’ -> ‘/tmp/Demo-test/core’
‘site/’ -> ‘/tmp/Demo-test/site’
‘admin/’ -> ‘/tmp/Demo-test/admin’
‘pom.xml’ -> ‘/tmp/Demo-test/pom.xml’

As a result we have successfully moved the selected content:

[vamshi@linuxcent DemoProject]$ ls /tmp/Demo-test/
admin core pom.xml site

Renaming multiple files with extensions

Here’s what we will be demonstrating in this tutorial, We will use a combination of tools like cut combining them with a for loop to accomplish our task in an iterative loop.

For simplicity sake let’s consider we have 10 files ending with .txt extension, as seen below

[vamshi@linuxcent ~]$ ls
file10.txt file1.txt file2.txt file3.txt file4.txt file5.txt file6.txt file7.txt file8.txt file9.txt

We will now rename them and append an extension of .txt to all the files as demonstrated below:

[vamshi@node02 source]$ for i in *.txt; do sh -c "mv $i `echo $i| cut -d'.' -f1 `.html" ; done
[vamshi@linuxceent ~]$ ls
file10.html file1.html file2.html file3.html file4.html file5.html file6.html file7.html file8.html file9.html

Using the rename command to rename the file extensions.

The linux rename command takes the arguments

We have here 10 files with .html extension

[vamshi@linuxcent ~]$ rename .html .doc *
[vamshi@linuxcent ~]$ ls
file10.doc file1.doc file2.doc file3.doc file4.doc file5.doc file6.doc file7.doc file8.doc file9.doc

While we also might have many other files in another extension format and we can change thrir extension format in the following method.
Suppose have 3 files with .txt extension as file11.txt file12.txt file13.txt and remaining files with .doc extension, they all can be renamed to .html as per the following format.

[vamshi@linuxcent source]$ ls
file10.doc file11.txt file12.txt file13.txt file1.doc file2.doc file3.doc file4.doc file5.doc file6.doc file7.doc file8.doc file9.doc
[vamshi@linuxcent ~]$ ls
file10.doc file11.txt file12.txt file13.txt file1.doc file2.doc file3.doc file4.doc file5.doc file6.doc file7.doc file8.doc file9.doc
[vamshi@linuxcent ~]$ rename .doc .txt .html *
[vamshi@node02 source]$ ls
file10.html file11.html file12.html file13.html file1.html file2.html file3.html file4.html file5.html file6.html file7.html file8.html file9.html