File operations in Linux

If you are using Linux, Ubuntu, Mac or any Linux-based operating system then you realize that sometimes directory or file operations are not only tedious but also time-consuming tasks. So here we will discuss all file operations which can use a lot. But First, understand the file. It is just like a container that can store either data or information.
So we have a list of tasks for the file operation –

Creation

To create a new file, use either the touch or vim command. But we will use the touch command for file creation.
touch [option] file_name


mkdir LearnLinux
cd LearnLinux
touch index.html
ls
index.html

What else when we need to create multiple files? So we can also achieve this using space between two directories. Like.


touch home.html about.html
ls
about.html home.html  index.html

Permission

We can also create files and set the user’s required permission.


touch app.js
chmod 775 app.js
ls -l app.js
-rwxrwxr-x  1 wayofwebs  staff  0 Sep 25 12:00 app.js

Deletion

To remove a file, use the rm command.
rm [option] file_name


ls
about.html app.js home.html index.html
rm home.html
ls
about.html app.js index.html

Sometimes we need to remove multiple files that time we can also use the rm command.


ls
about.html app.js index.html
rm about.html app.js
ls
index.html

If all files have the same extension then you can use regex for the deletion of files.


ls
index.html
touch about.html
ls
about.html index.html
rm *.html
ls


Move

To move any file from one directory to another, use the mv command.
mv source_file target_directory


touch app.js
ls
app.js
mkdir js
ls
app.js js
mv app.js js
ls
js
ls js
app.js

We can also move multiple files.


touch util.js func.js
ls
func.js js util.js
mv func.js util.js js
ls
js
ls js
app.js  func.js util.js

-f can be used to move forcefully.

Copy

To create a replica of any file or overwrite an existing one, use the cp command.
cp source_file target_file/target_directory


rm -r js
mkdir js
ls
js
touch app.js
ls
app.js js
cp app.js js
ls
app.js js
ls js
app.js

Note: If target_file does not exist then this command will create a new copy of source_file else it will overwrite source_file.

We can also create a copy of multiple files.
cp source_file1 source_file2 target_directory


touch util.js func.js
ls
app.js func.js js util.js
ls js
app.js
cp func.js util.js js
ls
app.js func.js js util.js
ls js
app.js func.js util.js

Rename

Renaming the file means changing the name of the file. Here we will use the mv command.
mv source_file_name target_file_name
Note that by default mv command overwrite if target_file_name already exists.


rm *.js
ls
js
rm -r js
touch app.js
ls
app.js
mv app.js main.js
main.js

You May Also Like

About the Author: Pankaj Bisht