0% found this document useful (0 votes)
19 views

Linux Unit 3 notes

This document provides a comprehensive guide on handling ordinary files in Linux, covering commands such as cat, cp, mv, rm, wc, cmp, comm, and diff, along with their syntax and examples. It also explains file attributes, permissions, and how to change them using the chmod command, including octal notations. Additionally, it discusses the grep family of commands for searching text within files, detailing their usage and options.

Uploaded by

rekhadhone4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Linux Unit 3 notes

This document provides a comprehensive guide on handling ordinary files in Linux, covering commands such as cat, cp, mv, rm, wc, cmp, comm, and diff, along with their syntax and examples. It also explains file attributes, permissions, and how to change them using the chmod command, including octal notations. Additionally, it discusses the grep family of commands for searching text within files, detailing their usage and options.

Uploaded by

rekhadhone4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

LINUX COMMAND II

Handling Ordinary Files:


An ordinary file is a file on the system that contains data, text, or program instructions. In this tutorial, you look
at working with ordinary files. An ordinary file is a file on the system that contains data, text, or program
instructions. In this tutorial, you look at working with ordinary files.

Cat command:

• cat is one of the most frequently used commands on Unix-like operating systems.

• It has three related functions with regard to text files: displaying them, combining copies of them and creating
new ones.

cat: Concatenate files and print to std. output.


 Syntax: cat [OPTION]…[FILE]
 Example: Create file1 with entered content
 $ cat > file1
 Hello
 ^D

cp: Copy files


 Syntax: cp [OPTION]source destination
 Example: Copies the contents from file1 to file2 and the contents of file1 are retained
 $ cp file1 file2

mv: Move files or rename files


 Syntax: mv [OPTION]source destination
 Example: Create empty files called ‘file1’ and ‘file2’
 $ mv file1 file2

rm: Remove files and directories


 Syntax: rm [OPTION]…[FILE]
 Example: Delete file1
 $ rm file1

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 Filename
wc --char filename - To show hidden char
wc --lines filename - To show file lines

cmp : command in Linux/UNIX is used to compare the two files byte by byte and helps you to find out
whether the two files are identical or not.
 When cmp is used for comparison between two files, it reports the location of the first mismatch to
the screen if difference is found and if no difference is found i.e the files compared are identical.
 cmp displays no message and simply returns the prompt if the files compared are identical.
Syntax:
cmp Filename1 Filename2
comm: comm compare two sorted files line by line and write to standard output; the lines that are
common and the lines that are unique.
Syntax:
comm Filename1 Filename2
diff: diff stands for difference. This command is used to display the differences in the files by
comparing the files line by line. Unlike its fellow members, cmp and comm, it tells us which lines in one
file have is to be changed to make the two files identical.
The important thing to remember is that diff uses certain special symbols and instructions that are
required to make two files identical. It tells you the instructions on how to change the first file to make it
match the second file.
Special symbols are:
a: add
c: change
d: delete
Syntax:
diff [options] File1 File2
OR
diff filename1 filename2

Attributes in Linux
Some filesystems support additional attributes (other than those described in the preceding sections). In
particular, some Linux-native filesystems support several attributes that you can adjust with the chattr
command. The files and directories can have the following attributes:

 a - append only
 c - compressed
 d - no dump
 e - extent format
 i - immutable
 j - data journaling
 s - secure deletion
 t - no tail-merging
 u - undeletable
 A - no atime updates
 D - synchronous directory updates
 S - synchronous updates
 T - top of directory hierarchy

Define each file attributes


 a - append only: this attribute allows a file to be added to, but not to be removed. It prevents
accidental or malicious changes to files that record data, such as log files.
 c - compressed: it causes the kernel to compress data written to the file automatically and
uncompress it when it’s read back.
 d - no dump: it makes sure the file is not backed up in backups where the dump utility is used
 e - extent format: it indicates that the file is using extents for mapping the blocks on disk.
 i - immutable: it makes a file immutable, which goes a step beyond simply disabling write access
to the file. The file can’t be deleted, links to it can’t be created, and the file can’t be renamed.
 j - data journaling: it ensures that on an Ext3 file system the file is first written to the journal and
only after that to the data blocks on the hard disk.
 s - secure deletion: it makes sure that recovery of a file is not possible after it has been deleted.
 t - no tail-merging: Tail-merging is a process in which small data pieces at a file’s end that don’t
fill a complete block are merged with similar pieces of data from other files.
 u - undeletable: When a file is deleted, its contents are saved which allows a utility to be
developed that works with that information to salvage deleted files.
 A - no atime updates: Linux won’t update the access time stamp when you access a file.
 D - synchronous directory updates: it makes sure that changes to files are written to disk
immediately, and not to cache first.
 S - synchronous updates: the changes on a file are written synchronously on the disk.
 T - and top of directory hierarchy: A directory will be deemed to be the top of directory
hierarchies for the purposes of the Orlov block allocator.
Syntax:
$ lsattr
$ lsattr
-----a-----------e- ./file1
----i------------e- ./hello_dir
-----------------e- ./usrcopy
-----------------e- ./special_characters
-----------------e- ./file3
-----------------e- ./contents
-----------------e- ./hard_link
-----------------e- ./usrlisting

File Permissions:
When you execute an “ls” command, you are not given any information about the security of the files,
because by default “ls” only lists the names of files. You can get more information by using an “option”
with the “ls” command. All options start with a ‘-‘. For example, to execute “ls” with the “long listing”
option, you would type ls -l
When you do so, each file will be listed on a separate line in long format. There is an example in the
window below.

There’s a lot of information in those lines.


1. The first character will almost always be either a ‘-‘, which means it’s a file, or a ‘d’, which means it’s
a directory.
2. The next nine characters (rw-r–r–) show the security; we’ll talk about them later.
3. The next column shows the owner of the file. In this case it is me, my userID is “aditya314”.
4. The next column shows the group owner of the file. In my case I want to give the “aditya314” group
of people special access to these files.
5. The next column shows the size of the file in bytes.
6. The next column shows the date and time the file was last modified.
7. And, of course, the final column gives the filename.
Deciphering the security characters will take a bit more work.

Understanding the security permissions


First, you must think of those nine characters as three sets of three characters (see the box at the
bottom). Each of the three “rwx” characters refers to a different operation you can perform on the file.

--- --- ---


rwx rwx rwx
user group other

Read, write, execute and –

The ‘r’ means you can “read” the file’s contents.


The ‘w’ means you can “write”, or modify, the file’s contents.
The ‘x’ means you can “execute” the file. This permission is given only if the file is a program.
If any of the “rwx” characters is replaced by a ‘-‘, then that permission has been revoked.

User, group and others

user – The user permissions apply only the owner of the file or directory, they will not impact the actions
of other users.
group – The group permissions apply only to the group that has been assigned to the file or directory,
they will not effect the actions of other users.
others – The others permissions apply to all other users on the system, this is the permission group that
you want to watch the most.

Reading the security permissions

For example, consider that the user’s permissions for some files is “rw-” as the first three characters.
This means that the owner of the file (“aditya314”, i.e. me) can “read” it (look at its contents) and “write”
it (modify its contents). I cannot execute it because it is not a program; it is a text file.
If “r-x” is the second set of 3 characters it means that the members of the group “aditya314” can only
read and execute the files.
The final three characters show the permissions allowed to anyone who has a UserID on this Linux
system. Let us say we have the permission (“r–“). This means anyone in our Linux world can read, but
they cannot modify the contents of the files or execute it.

Changing security permissions


The command you use to change the security permissions on files is called “chmod”, which stands for
“change mode”, because the nine security characters are collectively called the security “mode” of the
file.
1. The first argument you give to the “chmod” command is ‘u’, ‘g’, ‘o’. We use:
u for user
g for group
o for others,
you can also use a combination of them (u,g,o).
This specifies which of the three groups you want to modify.
2. After this use
a ‘+’ for adding
a ‘-‘ for removing
a “=” for assigning a permission.
3. Then specify the permission r,w or x you want to change.
Here also you can use a combination of r,w,x.
This specifies which of the three permissions “rwx” you want to modify
4. use can use commas to modify more permissions
5. Finally, the name of the file whose permission you are changing
An example will make this clearer.
For example, if you want to give “execute” permission to the world (“other”) for file “xyz.txt”, you would
start by typing
chmod o
Now you would type a ‘+’ to say that you are “adding” a permission.
chmod o+
Then you would type an ‘x’ to say that you are adding “execute” permission.
chmod o+x
Finally, specify which file you are changing.
chmod o+x xyz.txt

You can see the change in the picture below.

You can also change multiple permissions at once. For example, if you want to take all permissions
away from everyone, you would type

chmod ugo-rwx xyz.txt


The code above revokes all the read(r), write(w) and execute(x) permission from all user(u), group(g)
and others(o) for the file xyz.txt which results to this.

Another example can be this:

chmod ug+rw,o-x abc.mp4


The code above adds read(r) and write(w) permission to both user(u) and group(g) and revoke
execute(x) permission from others(o) for the file abc.mp4.
Something like this:

chmod ug=rx,o+r abc.c


assigns read(r) and execute(x) permission to both user(u) and group(g) and add read permission to
others for the file abc.c.
There can be numerous combinations of file permissions you can invoke, revoke and assign. You can
try some in your linux system.

The octal notations


You can also use octal notations like this.

Using the octal notations table instead of ‘r’, ‘w’ and ‘x’. Each digit octal notation can be used of either of
the group ‘u’,’g’,’o’.
So, the following work the same.
chmod ugo+rwx [file_name]
chmod 777 [file_name]
Both of them provides full read write and execute permission (code=7) to all the group.
Same is the case with this..

chmod u=r,g=wx,o=rx [file_name]


chmod 435 [file_name]
Both the codes give read (code=4) permission to user, write and execute (code=3) for group and read
and execute (code=5) for others.
And even this…

chmod 775 [file_name]


chmod ug+rwx,o=rx [file_name]

Both the commands give all permissions (code=7) to user and group, read and execute (code=5) for
others.

The grep family consists of the commands grep, egrep, and fgrep. The grep command globally searches for
regular expressions in files and prints all lines that contain the expression. The egrep and fgrep commands are
simply variants of grep. The egrep command is an extended grep, supporting more regular expression
metacharacters. The fgrep command, called fixed grep, and sometimes fast grep, treats all characters as
literals; that is, regular expression metacharacters aren't special—they match themselves. The Free Software
Foundation provides a free version of grep, called GNU grep. These versions of grep are the ones used ...

Grep Command in Linux/Unix with Examples


The 'grep' command stands for "global regular expression print". grep command filters the content of a file
which makes our search easy.

grep with pipe

The 'grep' command is generally used with pipe (|).

Syntax:

command | grep <searchWord>

Example:

cat marks.txt | grep 9


Look at the above snapshot, grep command filters all the data containing '9'.

grep without pipe


It can be used without pipe also.

Syntax:

grep <searchWord> <file name>

Example:

grep 9 marks.txt

Look at the above snapshot, grep command do the same work as earlier example but without pipe.

grep options
o grep -vM: The 'grep -v' command displays lines not matching to the specified word.

Syntax:

grep -v <searchWord> <fileName>

Example:
grep -v 9 marks.txt

Look at the above snapshot, command "grep -v 9 marks.txt" displays lines hwich don't contain our
search word '9'.

o grep -i: The 'grep -i' command filters output in a case-insensitive way.

Syntax:

grep -i <searchWord> <fileName>

Example:

grep -i red exm.txt

Look at the above snapshot, command "grep -i red exm.txt" displays all lines containing 'red' whether
in upper case or lower case.

o grep -A/ grep -B/ grep -C

grep -A command is used to display the line after the result.

grep -B command is used to display the line before the result.

grep -C command is used to display the line after and line before the result.

You can use (A1, A2, A3.....)(B1, B2, B3....)(C1, C2, C3....) to display any number of lines.

Syntax:

1. grep -A<lineNumber> <searchWord> <fileName>


2. grep -B<lineNumber> <searchWord> <fileName>
3. grep -C<lineNumber> <searchWord> <fileName>
Example:

grep -A1 yellow exm.txt


grep -B1 yellow exm.txt
grep -C1 yellow exm.txt

Look at the above snapshot, command "grep -A1 yellow exm.txt" displays searched line with next
succeeding line, command "grep -B1 yellow exm.txt" displays searched line with one preceding line and
command "grep -C1 yellow exm.txt" displays searched line with one preceding and succeeding line.

egrep command in Linux with examples


egrep is a pattern searching command which belongs to the family of grep functions. It works the same
way as grep -E does. It treats the pattern as an extended regular expression and prints out the lines
that match the pattern. If there are several files with the matching pattern, it also displays the file names
for each line. Syntax:
egrep [ options ] 'PATTERN' files
Example:

Note: The egrep command used mainly due to the fact that it is faster than the grep command. The
egrep command treats the meta-characters as they are and do not require to be escaped as is the case
with grep. This allows reducing the overhead of replacing these characters while pattern matching
making egrep faster than grep or fgrep. Options: Most of the options for this command are same
as grep.
 -c: Used to counts and prints the number of lines that matched the pattern and not the lines.
 -v: It prints the lines that does not match with the pattern

 -i: Ignore the case of the pattern while matching

 -l: Prints only the names of the files that matched. It does not mention the matching line numbers
or any other information.

 -L: Prints only the names of the files that did not have the pattern. Opposite of
l flag.

 -e: Allows to use a ‘-‘ sign in the beginning of the pattern. If not mentioned the shell tries to execute
the pattern as an option and returns an error.

 -w: Prints only those lines that contain the whole words. Word-constituent characters are letters,
digits and underscore. The matching substring must be separated by non-word constituent
characters.

 -x: Prints only those lines that matches an entire line of the file

 -m NUMBER: Continue to search for matches till the count reaches NUMBER mentioned as
Argument.
 -o: Prints only the matched parts of the line and not the entire line for each match.

-n: Prints each matched line along with the respective line numbers. For multiple files, prints the
file names along with line
numbers.

 -r: Recursively search for the pattern in all the files of the directory. The last argument is the
directory to check. ‘.’ (dot) represents the current directory

fgrep command in Linux with examples


The fgrep filter is used to search for the fixed-character strings in a file. There can be multiple files also
to be searched. This command is useful when you need to search for strings which contain lots of
regular expression metacharacters, such as “^”, “$”, etc.

Syntax:
fgrep [options] [ -e pattern_list] [pattern] [file]

Consider below file as input. Here it is create using cat command and “name of the file is para”.

Hi, @re you usin.g geeks*forgeeks for learni\ng computer science con/cepts.
Geeks*forgeeks is best for learni\ng.

Options with Description and Example:


 -c : It is used to print only a count of the lines which contain the pattern.
 $fgrep -c "usin.g" para

 -h : Used to display the matched lines.


 fgrep -h "usin.g" para
 -i : During comparisons, it will ignore upper/lower case distinction.
 fgrep -i "geeks*forgeeks" para

 -l : Used to print the names of files with matching lines once, separated by new-lines. It will not
repeat the names of files when the pattern is found more than once.
 fgrep -l "geeks*forgeeks" para para2

 -n : It is used precede each line by its line number in the file (first line is 1).
 $ fgrep -n "learni\ng" para

 -s : It will only display the error messages.

 -v : Print all lines except those contain the pattern.


 fgrep -v "@re" para

 -x : Print only lines matched entirely.


 fgrep -x "@re" para

 -e pattern_list : Search for a string in pattern-list (useful when the string begins with a “-“).

 -f pattern-file : Take the list of patterns from pattern-file.

 pattern : Specify a pattern to be used during the search for input.


 file : A path name of a file to be searched for the patterns. If no file operands are specified, the
standard input will be used.

Linux tr
The command 'tr' stands for 'translate'. It is used to translate, like from lowercase to uppercase and vice versa
or new lines into spaces.

Syntax:

1. command | tr <'old'> <'new'>

Change Case
The 'tr' command can change case.

Syntax:

command | tr <'old'> <'new'>

Example:

cat exm.txt | tr 'prcu' 'PRCU'

Look at the above snapshot, all p,r,c,u are converted into upprecase P,R,C,U.

Remove New Lines


To write all the lines into a single line we have to translate all new lines into spaces.

Syntax:

command | tr <'\n'> <' '>

Example:

cat exm.txt | tr '\n' ' '


tr Options
o tr -s : The 'tr -s' command squeezes the occurence of multiple characters into one.

Syntax:

command | tr -s <'letter'>

Example:

cat jtp.txt | tr -s 'l'


cat spaces.txt | tr -s ' '

Look at the above snapshot, command "cat jtp.txt | tr -s 'l'" has squeezed all the letters 'l' into one and
command "cat spaces.txt | tr -s ' '" has squeezed all the spaces into single space.

o tr rot13: This command encrypts the text. It is case-sensitive.

Example:

cat exm.txt | tr 'a-z' 'nopqrstuvwxyzabcdefghijklm'


cat exm.txt | tr 'a-z' 'n-za-m'
Look at the above snapshot, all the letters are encrypted according to the command. But letter 'A' and 'M' are
not encrypted as they are in upper case.

o tr -d: The 'tr -d' command is used to delete characters.

Syntax:

command | tr -d <letter>

Example:

cat exm.txt | tr -d o

Look at the above snapshot, all the 'o' letters are deleted from the file 'exm.txt'.

You might also like