Linux Unit II
Linux Unit II
Linux Unit II
Creating an alias :
Syntax:
alias name="value"
2. Schedule a job for the coming Monday at a time twenty minutes later than
the current time:
at Monday +20 minutes
3. Schedule a job to run at 1:45 Aug 12 2020:
at 1:45 081220
4. Schedule a job to run at 3pm four days from now:
at 3pm + 4 days
5. Schedule a job to shutdown the system at 4:30 today:
# echo "shutdown -h now" | at -m 4:30
6. Schedule a job to run five hour from now:
at now +5 hours
7. at -r or atrm command is used to deletes job , here used to deletes job 11 .
at -r 11
or
atrm 11
job : Job number of the job which is to be deleted. To see the list of the pending
jobs use following:
1. Creating Files
touch command can be used to create a new file. It will create and open a new blank
file if the file with a filename does not exist. And in case the file already exists then
the file will not be affected.
$touch filename
cat command can be used to display the contents of a file. This command will
display the contents of the ‘filename’ file. And if the output is very large then we
could use more or less to fit the output on the terminal screen otherwise the content
of the whole file is displayed at once.
$cat filename
3. Copying a File
cp command could be used to create the copy of a file. It will create the new file in
destination with the same name and content as that of the file ‘filename’.
$cp source/filename destination/
4. Moving a File
mv command could be used to move a file from source to destination. It will remove
the file filename from the source folder and would be creating a file with the same
name and content in the destination folder.
$mv source/filename destination/
5. Renaming a File
rm command could be used to delete a file. It will remove the filename file from the
directory.
$rm filename
1. Creating Directories
We will now understand how to create directories. Directories are created by the
following command −
$mkdir dirname
Here, directory is the absolute or relative pathname of the directory you want to
create. For example, the command −
$mkdir mydir
$
Creates the directory mydir in the current directory. Here is another example −
$mkdir /tmp/test-dir
$
This command creates the directory test-dir in the /tmp directory.
The mkdir command produces no output if it successfully creates the requested
directory.
If you give more than one directory on the command line, mkdir creates each of the
directories. For example, −
$mkdir docs pub
Creates the directories docs and pub under the current directory.
2. Changing Directories
You can use the cd command to do more than just change to a home directory. You
can use it to change to any directory by specifying a valid absolute or relative path.
The syntax is as given below −
$cd dirname
Here, dirname is the name of the directory that you want to change to. For example,
the command −
$cd /usr/local/bin
$Changes to the directory /usr/local/bin. From this directory, you
can cd to the directory /usr/home/amrood using the following relative
path −
$cd ../../home/amrood
3. Renaming Directories
The mv (move) command can also be used to rename a directory. The syntax is as
follows −
$mv olddir newdir
$
You can rename a directory mydir to yourdir as follows −
$mv mydir yourdir
$
rmdir command is used remove empty directories from the filesystem in Linux. The
rmdir command removes each and every directory specified in the command line
only if these directories are empty. So if the specified directory has some directories
or files in it then this cannot be removed by rmdir command.
Syntax:
rmdir [-p] [-v | –verbose] [–ignore-fail-on-non-empty] directories …
Options:
–help: It will print the general syntax of the command along with the various
options that can be used with the rmdir command as well as give a brief
description about each option.
rmdir -p: In this option each of the directory argument is treated as a pathname of
which all components will be removed, if they are already empty, starting from the
last component.
rmdir -v, –verbose: This option displays verbose information for every directory
being processed.
rmdir –ignore-fail-on-non-empty: This option do not report a failure which occurs
solely because a directory is non-empty. Normally, when rmdir is being instructed
to remove a non-empty directory, it simply reports an error. This option consists of
all those error messages.
rmdir –version: This option is used to display the version information and exit.
Example 1: This will first remove the child directory and then remove the parent
directory.
rmdir -p mydir/mydir1
Example 2: Remove the directories mydir1, mydir2, and mydir3, if they are empty.
If any of these directories are not empty, then an error message will be printed for
that directory, and the other directories will be removed.
rmdir mydir1 mydir2 mydir3
ls -a In Linux, hidden files start with . (dot) symbol and they are not visible in
the regular directory. The (ls -a) command will enlist the whole list of
the current directory including the hidden files.
ls -lh This command will show you the file sizes in human readable format.
Size of the file is very difficult to read when displayed in terms of byte.
The (ls -lh)command will give you the data in terms of Mb, Gb, Tb, etc.
ls -lhS If you want to display your files in descending order (highest at the top)
according to their size, then you can use (ls -lhS) command.
ls -l - -block- It is used to display the files in a specific size format. Here, in [SIZE]
size=[SIZE] you can assign size according to your requirement.
ls -g or ls -lG With this you can exclude column of group information and owner.
ls -li This command prints the index number if file is in the first column.
ls -lX It will group the files with same extensions together in the list.
ls -lt It will sort the list by displaying recently modified filed at top.
In the above example, you can see the whole list of files, including the hidden files.
Linux ls -l command
The ls command will only display the files. But if you want your files to be displayed
in a long list format, then you can use ls -l command.
Here, as you can see the list in long list format.
Columns above indicate specific things:
Column 1 indicates information regarding file permission.
Column 2 indicates the number of links to the file.
Column 3 & 4 indicates the owner and group information.
Column 5 indicayes size of the file in bytes.
Column 6 shows th date and time on which the file was recently modified.
Column 7 shows the file or directory name.
Linux ls -l --block-size=[SIZE]
If you want to display the file size of your list in a particular format or size, then you
can use this command. Just put the size in place of [SIZE] as per your requirement.
Syntax:
Linux ls -lG
If you don't want to display the group information in your list then you can exclude
this column with the help of this command.
Here group column is excluded.
Linux ls --color=[VALUE]
This command is used to colorize and decolorize the list. If you replace the [VALUE]
by 'auto', it will display the colored list. But, if you will replace the [VALUE] by
'never', it will decolorize the list.
Syntax:
ls --color=[VALUE]
Linux ls ~
Linux ls ~ command shows the contents of the home directory. Let us see the example
of ls ~ command.
Linux ls ../
This command contains the list of the parent directory.
In the given example, our current directory is Downloads, and by using ls ../ command,
we have listed out the content of its parent directory "home directory".
6. Tree command
Options :
–help : Outputs a verbose usage listing.
–version : Outputs the version of tree.
-a : All files are printed. By default, tree does not print hidden files (those beginning
with a dot `.’). In no event does tree print the file system constructs `.’ (current
directory) and `..’ (previous directory).
-d : List directories only.
-f : Prints the full path prefix for each file.
-i : Tree will not print the indentation lines. Useful when used in conjunction with the -
f option.
-l : Follows symbolic links to directories as if they were directories. Links that would
result in a recursive loop are avoided.
-x : Stay on the current file system only, as with find -xdev.
-P pattern : List only those files that match the wild-card pattern.
Note : you must use the -a option to also consider those files beginning with a dot `.’
for matching. Valid wildcard operators are `*’ (any zero or more characters), `?’ (any
single character), `[…]’ (any single character listed between brackets (optional –
(dash) for character range may be used: ex: [A-Z]), and `[^…]’ (any single character
not listed in brackets) and `|’ separates alternate patterns.
-I pattern : Do not list those files that match the wild-card pattern.
–prune : Makes tree prune empty directories from the output, useful when used in
conjunction with -P or -I.
–filelimit # : Do not descend directories that contain more than # entries.
–timefmt format : Prints (implies -D) and formats the date according to the format
string which uses the strftime syntax.
–noreport : Omits printing of the file and directory report at the end of the tree listing.
-p : Print the protections for each file (as per ls -l).
-s : Print the size of each file along with the name.
-u : Print the username, or UID # if no username is available, of the file.
-g : Print the group name, or GID # if no group name is available, of the file.
-D : Print the date of the last modification time for the file listed.
–inodes : Prints the inode number of the file or directory
–device : Prints the device number to which the file or directory belongs
-F : Append a `/’ for directories, a `=’ for socket files, a `*’ for executable files and a
`|’ for FIFO’s, as per ls -F
-q : Print non-printable characters in file names as question marks instead of the
default carrot notation.
-N : Print non-printable characters as is instead of the default carrot notation.
-r : Sort the output in reverse alphabetic order.
-t : Sort the output by last modification time instead of alphabetically.
–dirsfirst : List directories before files.
-n : Turn colorization off always, over-ridden by the -C option.
-C : Turn colorization on always, using built-in color defaults if the LS_COLORS
environment variable is not set. Useful to colorize output to a pipe.
-A : Turn on ANSI line graphics hack when printing the indentation lines.
-S : Turn on ASCII line graphics (useful when using linux console mode fonts). This
option is now equivalent to `–charset=IBM437′ and will eventually be depreciated.
-L level : Max display depth of the directory tree.
-R : Recursively cross down the tree each level directories (see -L option), and at each
of them execute tree again adding `-o 00Tree.html’ as a new option.
-H baseHREF : Turn on HTML output, including HTTP references. Useful for ftp
sites. baseHREF gives the base ftp location when using HTML output. That is, the
local directory may be `/local/ftp/pub’, but it must be referenced as `ftp://host-
name.organization.domain/pub’ (baseHREF should be
`ftp://hostname.organization.domain’). Hint: don’t use ANSI lines with this option, and
don’t give more than one directory in the directory list. If you want to use colors via
CSS stylesheet, use the -C option in addition to this option to force color output.
-T title : Sets the title and H1 header string in HTML output mode.
–charset charset : Set the character set to use when outputting HTML and for line
drawing.
–nolinks : Turns off hyperlinks in HTML output.
-o file name : Send output to file name.
Examples :
1. How to install tree in Unix/Linux.
By default the tree command is not installed. Type the following command to install
the same on a RHEL / CentOS / Fedora Linux using yum command :
# yum install tree
If you are using Debian / Mint / Ubuntu Linux, type the following apt-get command to
install the tree command :
$ sudo apt install tree
If you are using Apple OS X, type:
brew install tree
2. Display the tree hierarchy of a directory
$ tree -a ./GFG
Output :
In the given example the directory /home/shital/logs/ is a symbolic link for a target
directory /var/logs/
B)Binary pwd (/bin/pwd):
2. The grep filter searches a file for a particular pattern of characters, and displays
all lines that contain that pattern. The pattern that is searched in the file is referred to as
the regular expression (grep stands for global search for regular expression and print
out).
Syntax:
Options Description
-c : This prints only a count of the lines that match a pattern
-h : Display the matched lines, but do not display the filenames.
-i : Ignores, case for matching
-l : Displays list of a filenames only.
-n : Display the matched lines and their line numbers.
-v : This prints out all the lines that do not matches the pattern
-e exp : Specifies expression with this option. Can use multiple times.
-f file : Takes patterns from file, one per line.
-E : Treats pattern as an extended regular expression (ERE)
-w : Match whole word
-o : Print only the matched parts of a matching line,
with each such part on a separate output line.
Sample Commands
Consider the below file as an input.
3. Display the file names that matches the pattern : We can just display the files that
contains the given string/pattern.
$grep -l "unix" *
or
geekfile.txt
4. Checking for the whole words in a file : By default, grep matches the given
string/pattern even if it is found as a substring in a file. The -w option to grep makes it
match only the whole words.
unix
unix
unix
unix
unix
unix
6. Show line number while displaying the output using grep -n : To show the line
number of file with the line matched.
$cat pattern.txt
Agarwal
Aggarwal
Agrawal
Above command prints starting from first character to end. Here in command only
starting
position is specified and the ending position is omitted.
$ cut -c -5 state.txt
Andhr
Aruna
Assam
Bihar
Chhat
Above command prints starting position to the fifth character. Here the starting position
is omitted and the ending position is specified.
3. -f (field): -c option is useful for fixed-length lines. Most unix files doesn’t have
fixed-length lines. To extract the useful information you need to cut by fields rather
than columns. List of the fields number specified must be separated by comma. Ranges
are not described with -f option. cut uses tab as a default field delimiter but can also
work with other delimiter by using -d option.
Note: Space is not considered as delimiter in UNIX.
Syntax:
$cut -d "delimiter" -f (field number) file.txt
Like in the file state.txt fields are separated by space if -d option is not used then it
prints whole line:
$ cut -f 1 state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
If -d option is used then it considered space as a field separator or delimiter:
$ cut -d " " -f 1 state.txt
Andhra
Arunachal
Assam
Bihar
Chhattisgarh
Command prints field from first to fourth of each line from the file.
Command:
$ cut -d " " -f 1-4 state.txt
Output:
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
4. –complement: As the name suggests it complement the output. This option can be
used in the combination with other options either with -f or with -c.
$ cut --complement -d " " -f 1 state.txt
Pradesh
Pradesh
Assam
Bihar
Chhattisgarh
1. How to use tail with pipes(|): The cut command can be piped with many other
commands of the unix. In the following example output of the cat command is given as
input to the cut command with -f option to sort the state names coming from file
state.txt in the reverse order.
$ cat state.txt | cut -d ' ' -f 1 | sort -r
Chhattisgarh
Bihar
Assam
Arunachal
Andhra
It can also be piped with one or more filters for additional processing. Like in the
following example, we are using cat, head and cut command and whose output is stored
in the file name list.txt using directive(>).
$ cat state.txt | head -n 3 | cut -d ' ' -f 1 > list.txt
$ cat list.txt
Andhra
Arunachal
Assam
wc command
wc stands for word count. As the name implies, it is mainly used for counting purpose.
It is used to find out number of lines, word count, byte and characters count in the
files specified in the file arguments.
By default it displays four-columnar output.
First column shows number of lines present in a file specified, second column
shows number of words present in the file, third column shows number of characters
present in file and fourth column itself is the file name which are given as argument.
Syntax:
wc [OPTION]... [FILE]...
Let us consider two files having name state.txt and capital.txt containing 5 names of the
Indian states and capitals respectively.
$ cat state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
$ cat capital.txt
Hyderabad
Itanagar
Dispur
Patna
Raipur
Passing only one file name in the argument.
$ wc state.txt
5 7 63 state.txt
OR
$ wc capital.txt
5 5 45 capital.txt
Passing more than one file name in the argument.
$ wc state.txt capital.txt
5 7 63 state.txt
5 5 45 capital.txt
10 12 108 total
Note : When more than file name is specified in argument then command will display
four-columnar output for all individual files plus one extra row displaying total number
of lines, words and characters of all the files specified in argument, followed by
keyword total.
Options:
1. -l: This option prints the number of lines present in a file. With this option wc
command displays two-columnar output, 1st column shows number of lines present in a
file and 2nd itself represent the file name.
With one file name
$ wc -l state.txt
5 state.txt
Applications of wc Command
1. To count all files and folders present in directory: As we all know ls command in
unix is used to display all the files and folders present in the directory, when it is piped
with wc command with -l option it display count of all files and folders present in
current directory.
$ ls gfg
a.txt
b.txt
c.txt
d.txt
e.txt
geeksforgeeks
India
$ ls gfg | wc -l
7
2. Display number of word count only of a file: We all know that this can be done
with wc command having -w option, wc -w file_name, but this command shows two-
columnar output one is count of words and other is file name.
$ wc -w state.txt
7 state.txt
Output :
abhishek
chitransh
divyam
harsh
naveen
rajan
satish
Note: This command does not actually change the input file, i.e. file.txt.
Sort function with mix file i.e. uppercase and lower case: When we have a mix file with
both uppercase and lowercase letters then first the upper case letters would be sorted
following with the lower case letters.
Example:
Create a file mix.txt
Command :
$ cat > mix.txt
abc
apple
BALL
Abc
bat
Now use the sort command
Command :
$ sort mix.txt
Output :
Abc
BALL
abc
apple
bat
Options with sort function:
1. -o Option: Unix also provides us with special facilities like if you want to write
the output to a new file, output.txt, redirects the output like this or you can also use the
built-in sort option -o, which allows you to specify an output file.
Using the -o option is functionally the same as redirecting the output to a file.
Note: Neither one has an advantage over the other.
Example: The input file is the same as mentioned above.
Syntax:
$ sort inputfile.txt > filename.txt
$ sort -o filename.txt inputfile.txt
Command:
$ sort file.txt > output.txt
$ sort -o output.txt file.txt
$ cat output.txt
Output :
abhishek
chitransh
divyam
harsh
naveen
rajan
satish
2. -r Option: Sorting In Reverse Order: You can perform a reverse-order sort using the -
r flag. the -r flag is an option of the sort command which sorts the input file in reverse
order i.e. descending order by default.
Example: The input file is the same as mentioned above.
Syntax :
$ sort -r inputfile.txt
Command :
$ sort -r file.txt
Output :
satish
rajan
naveen
harsh
divyam
chitransh
abhishek
3. -n Option: To sort a file numerically used –n option. -n option is also predefined in
Unix as the above options are. This option is used to sort the file with numeric data
present inside.
Example :
Let us consider a file with numbers:
Command :
$ cat > file1.txt
50
39
15
89
200
Syntax:
$ sort -n filename.txt
Command :
$ sort -n file1.txt
Output :
15
39
50
89
200
4. -nr option: To sort a file with numeric data in reverse order we can use the
combination of two options as stated below.
Example: The numeric file is the same as above.
Syntax :
$ sort -nr filename.txt
Command :
$ sort -nr file1.txt
Output :
200
89
50
39
15
5. -k Option: Unix provides the feature of sorting a table on the basis of any column
number by using -k option.
Use the -k option to sort on a certain column. For example, use “-k 2” to sort on the
second column.
Example :
Let us create a table with 2 columns
$ cat > employee.txt
manager 5000
clerk 4000
employee 6000
peon 4500
director 9000
guard 3000
Syntax :
$ sort -k filename.txt
Command :
$ sort -k 2n employee.txt
guard 3000
clerk 4000
peon 4500
manager 5000
employee 6000
director 9000
6. -c option: This option is used to check if the file given is already sorted or not &
checks if a file is already sorted pass the -c option to sort. This will write to standard
output if there are lines that are out of order. The sort tool can be used to understand if
this file is sorted and which lines are out of order
Example :
Suppose a file exists with a list of cars called cars.txt.
Audi
Cadillac
BMW
Dodge
Syntax :
$ sort -c filename.txt
Command :
$ sort -c cars.txt
Output :
sort: cars.txt:3: disorder: BMW
Note : If there is no output then the file is considered to be already sorted
7. -u option: To sort and remove duplicates pass the -u option to sort. This will write a
sorted list to standard output and remove duplicates.
This option is helpful as the duplicates being removed give us a redundant file.
Example: Suppose a file exists with a list of cars called cars.txt.
Audi
BMW
Cadillac
BMW
Dodge
Syntax :
$ sort -u filename.txt
Command :
$ sort -u cars.txt
$ cat cars.txt
Output :
Audi
BMW
Cadillac
Dodge
8. -M Option: To sort by month pass the -M option to sort. This will write a sorted list
to standard output ordered by month name.
Example:
Suppose the following file exists and is saved as months.txt
$ cat > months.txt
February
January
March
August
September
Syntax :
$ sort -M filename.txt
Using The -M option with sort allows us to order this file.
Command :
$ sort -M months.txt
$ cat months.txt
Output :
January
February
March
August
September
-f : This option does not wrap the long lines and displays them as such.
Example:
more -f sample.txt
-p : This option clears the screen and then displays the text.
Example:
more -p sample.txt
-c : This command is used to display the pages on the same area by overlapping the
previously displayed text.
Example:
more -c sample.txt
-s : This option squeezes multiple blank lines into one single blank line.
Example:
more -s sample.txt
+num : This option displays the text after the specified number of lines of the
document.
Example:
more +30 sample.txt
Using more to Read Long Outputs: We use more command after a pipe to see long
outputs. For example, seeing log files, etc.
cat a.txt | more
The more command takes the output of $ ls -l as its input. The net effect of this
command is that the output of ls -l is displayed one screen at a time. The pipe acts as a
container which takes the output of ls -l and gives it to more as input. This command
does not use a disk to connect standard output of ls -l to the standard input of more
because pipe is implemented in the main memory.
In terms of I/O redirection operators, the above command is equivalent to the following
command sequence.
$ ls -l -> temp
more -> temp (or more temp)
[contents of temp]
rm temp
Output :
4. Use ls and find to list and print all lines matching a particular pattern in matching
files.
$ ls -l | find ./ -type f -name "*.txt" -exec grep "program" {} \;
This command select files with .txt extension in the given directory and search for
pattern like “program” in the above example and print those ine which have program in
them.
Output :
5. Use cat, grep, tee and wc command to read the particular entry from user and store in
a file and print line count.
$ cat result.txt | grep "Rajat Dua" | tee file2.txt | wc -l
This command select Rajat Dua and store them in file2.txt and print total number of
lines matching Rajat Dua
Output :
5. Tools and utilites: find, locate, date, cal, gzip, gunzip,
zcat, man, tar
find command in linux
Finding Files by Name
In order to find a file by name, simply type:
find -name "File1"
This is a case sensitive search, so it returned just one file:
./File1
If we want to run a case insensitive search, we can do this:
find -iname "File1"
This search will return both uppercase and lowercase results:
./file1
./File1
What if we only want to return files with names that don’t contain a certain string?
Then we will use:
find -not -name "file"
This will return all files that don’t contain the string “file” in them, and is applicable to
other strings.
Finding Files by Type
If you want to search for files by type, you can do so with the following command:
find -type typequery
Some examples of file types are:
f: Regular file
d: Directory
l: Symbolic link
c: Character devices
b: Block devices
In order to find a regular file called “file1” use:
find -type f -name "file1"
Finding Files by Time
You can find files based on access time (-atime), modified time (-mtime), and change
time (-ctime) flags.
We can even find files based on permissions. This will list all files with 755
permissions:
find / -perm -755
By default, this will return any file that has the string “filename” in its location. To
locate files only on the name of the actual file, use the –basename option:
locate -b filename
You can also use the wildcard characters, such as *. To find all files ending in .html,
type:
locate *.html
You can use pipe or redirect to take the standard output of the locate command and send
it to the standard input of another command, or to file:
locate *.html | grep file1
or
locate *.html > listoffiles.txt
Command:
$date
Output:
Tue Oct 10 22:55:01 PDT 2017
Note : Here unix system is configured in pacific daylight time.
2:-u Option: Displays the time in GMT(Greenwich Mean Time)/UTC(Coordinated
Universal Time )time zone.
Command:
$date -u
Output :
Wed Oct 11 06:11:31 UTC 2017
3: –date or -d Option: Displays the given date string in the format of date. But this will
not affect the system’s actual date and time value.Rather it uses the date and time given
in the form of string.
Syntax:
Command:
$date --date="2/02/2010"
$date --date="Feb 2 2010"
Output:
Tue Feb 2 00:00:00 PST 2010
Tue Feb 2 00:00:00 PST 2010
4:Using –date option for displaying past dates:
Command:
$date --date="2 year ago"
Output:
Sat Oct 10 23:42:15 PDT 2015
Date and time of 5 seconds ago.
Command:
$date --date="5 sec ago"
Output:
Tue Oct 10 23:45:02 PDT 2017
Command:
$date --date="yesterday"
Output:
Mon Oct 9 23:48:00 PDT 2017
Command:
$date --date="2 month ago"
Output:
Thu Aug 10 23:54:51 PDT 2017
Command:
$date --date="10 day ago"
Output:
Sat Sep 30 23:56:55 PDT 2017
Command:
$date --date="next tue"
Output:
Tue Oct 17 00:00:00 PDT 2017
Command:
$date --date="2 day"
Output:
Fri Oct 13 00:05:52 PDT 2017
Command:
$date --date="tomorrow"
Output:
Thu Oct 12 00:08:47 PDT 2017
Date and time after 1 year on the current day.
Command:
$date --date="1 year"
Output:
Thu Oct 11 00:11:38 PDT 2018
6:-s or –set Option: To set the system date and time -s or –set option is used.
Syntax:
Command:
$date
Output:
Wed Oct 11 15:23:26 PDT 2017
Command:
$date --set="Tue Nov 13 15:23:34 PDT 2018"
$date
Output:
Tue Nov 13 15:23:34 PDT 2018
7:–file or -f Option: This is used to display the date string present at each line of file in
the date and time format.This option is similar to –date option but the only difference is
that in –date we can only give one date string but in a file we can give multiple date
strings at each line.
Syntax:
$date --file=file.txt
$date -r file.txt
We can modify the timestamp of a datefile by using touch command.
$touch datefile
$date -r datefile
Wed Oct 11 15:54:18 PDT 2017
//this is the current date and time
$touch datefile
//The timestamp of datefile is changed using touch command.
This was done few seconds after the above date command’s output.
$date -r datefile
Wed Oct 11 15:56:23 PDT 2017
//display last modified time of datefile
9: List of Format specifiers used with date command:
$date +%[format-option]
Examples:
Command:
$date "+%D"
Output:
10/11/17
Command:
$date "+%D %T"
Output:
10/11/17 16:13:27
Command:
$date "+%Y-%m-%d"
Output:
2017-10-11
Command:
$date "+%Y/%m/%d"
Output:
2017/10/11
Command:
$date "+%A %B %d %T %y"
Output:
Thursday October 07:54:29 12 17
Syntax:
cal [ [ month ] year]
The rectangular bracket means it is optional, so if used without an option, it will display
a calendar of the current month and year.
cal : Shows current month calendar on the terminal with the current date highlighted.
cal -y : Shows the calendar of the complete current year with the current date
highlighted.
cal 2018 | more : But year may not be visible in the same screen use more with cal use
spacebar to scroll down.
cal -3 : Shows calendar of previous, current and next month
cal -j : Shows the calendar of the current month in the Julian calendar format not in the
default Gregorian calendar format. In Julian calendar format, the date does not reset to 1
after every month’s end i.e. after 31st Jan, Feb will start as 32nd Feb, not as 1st Feb.
But in the Gregorian calendar format, the date is reset to 1 after every month’s end i.e
after 31st Jan, Feb will start as of 1st Feb.
Gzip Command in Linux
gzip command compresses files. Each single file is compressed into a single file. The
compressed file consists of a GNU zip header and deflated data.
If given a file as an argument, gzip compresses the file, adds a “.gz” suffix, and deletes
the original file. With no arguments, gzip compresses the standard input and writes the
compressed file to standard output.
Difference between Gzip and zip command in Unix and when to use which command
ZIP and GZIP are two very popular methods of compressing files, in order to save
space, or to reduce the amount of time needed to transmit the files across the network,
or internet.
In general, GZIP is much better compared to ZIP, in terms of compression, especially
when compressing a huge number of files.
The common practice with GZIP, is to archive all the files into a single tarball before
compression. In ZIP files, the individual files are compressed and then added to the
archive.
When you want to pull a single file from a ZIP, it is simply extracted, then
decompressed. With GZIP, the whole file needs to be decompressed before you can
extract the file you want from the archive.
When pulling a 1MB file from a 10GB archive, it is quite clear that it would take a lot
longer in GZIP, than in ZIP.
GZIP’s disadvantage in how it operates, is also responsible for GZIP’s advantage. Since
the compression algorithm in GZIP compresses one large file instead of multiple
smaller ones, it can take advantage of the redundancy in the files to reduce the file size
even further.
If you archive and compress 10 identical files with ZIP and GZIP, the ZIP file would be
over 10 times bigger than the resulting GZIP file.
Syntax :
gzip [Options] [filenames]
Example:
$ gzip mydoc.txt
This command will create a compressed file of mydoc.txt named as mydoc.txt.gz and
delete the original file.
Options :
-f option : Sometimes a file cannot be compressed. Perhaps you are trying to compress a
file called “myfile1” but there is already a file called “myfile1.gz”. In this instance, the
“gzip” command won’t ordinarily work.
To force the “gzip” command to do its stuff simply use -f option:
$ gzip -f myfile1.txt
This will forcefully compress a file named myfile.txt even if there already exists a file
named as myfile.txt.gz
-k option :By default when you compress a file using the “gzip” command you end up
with a new file with the extension “.gz”.If you want to compress the file and keep the
original file you have to run the gzip command with -k option:
$ gzip -k mydoc.txt
The above command would end up with a file called “mydoc.txt.gz” and “mydoc.txt”.
-L option : This option displays the gzip license.
$ gzip -L filename.gz
OUTPUT :
Apple gzip 264.50.1 (based on FreeBSD gzip 20111009)
Copyright (c) 1997, 1998, 2003, 2004, 2006 Matthew R. Green
All rights reserved.
-r option : This option can compress every file in a folder and its subfolders.This option
doesn’t create one file called foldername.gz. Instead, it traverses the directory structure
and compresses each file in that folder structure.
gzip -r testfolder
$ gzip -1 mydoc.txt
$ gzip -9 mydoc.txt
$ gzip -v mydoc.txt
OUTPUT :
new.txt: 18.2% -- replaced with new.txt.gz
-d option :This option allows to decompress a file using the “gzip” command.
$ gzip -d mydoc.txt.gz
zcat Command
Zcat is a command line utility for viewing the contents of a compressed file without
literally uncompressing it. It expands a compressed file to standard output allowing you
to have a look at its contents. In addition, zcat is identical to running gunzip -
c command. In this guide, we will explain zcat command examples for beginners.
1. The first example shows how to view contents of a normal file using cat command,
compress it using gzip command and view the contents of the zipped file using zcat as
shown.
$ cat users.list
$ gzip users.list
$ zcat users.list.gz
$ zcat -f users.list
$ zcat -l users.list.gz
To suppress all warnings, use the -q flag as shown.
$ zcat -q users.list.gz
$ man zcat
VI EDITOR
The VI editor is the most popular and classic text editor in the Linux family. Below, are
some reasons which make it a widely used editor –
vi Editing commands
i – Insert at cursor (goes into insert mode)
a – Write after cursor (goes into insert mode)
A – Write at the end of line (goes into insert mode)
ESC – Terminate insert mode
u – Undo last change
U – Undo all changes to the entire line
o – Open a new line (goes into insert mode)
dd – Delete line
3dd – Delete 3 lines.
D – Delete contents of line after the cursor
C – Delete contents of a line after the cursor and insert new text. Press ESC key to end
insertion.
dw – Delete word
4dw – Delete 4 words
cw – Change word
x – Delete character at the cursor
r – Replace character
R – Overwrite characters from cursor onward
s – Substitute one character under cursor continue to insert
S – Substitute entire line and begin to insert at the beginning of the line
~ – Change case of individual character
Note: You should be in the “command mode” to execute these commands. VI editor
is case-sensitive so make sure you type the commands in the right letter-case.
Moving within a file
k – Move cursor up
j – Move cursor down
h – Move cursor left
l – Move cursor right
You need to be in the command mode to move within a file. The default keys for
navigation are mentioned below else; You can also use the arrow keys on the
keyboard.
Saving and Closing the file
Shift+zz – Save the file and quit
:w – Save the file but keep it open
:q – Quit without saving
:wq – Save the file and quit
You should be in the command mode to exit the editor and save changes to the file.