Back
The grep command uses a search term to look through a file. It returns the full line that contains the search term .
For examples :
1. Search for the given string in a single file
Syntax:
$ grep "literal_string" filename
The basic usage of grep command is to search for a specific string in the specified file as shown below.
2. Checking for the given string in multiple files.
Syntax:
$ grep "string" FILE_PATTERN
3. Case insensitive search using grep -i
Syntax:
$ grep -i "string" FILE
This is also a basic usage of the grep. This searches for the given string/pattern case insensitively. So it matches all the words such as “the”, “THE” and “The” case insensitively as shown below.
4. Match regular expression in files
Syntax:
$ grep "REGEX" filename
This is a very powerful feature, if you can use use regular expression effectively. In the following example, it searches for all the pattern that starts with “lines” and ends with “empty” with anything in-between.
5. Checking for full words, not for sub-strings using grep -w
If you want to search for a word, and to avoid it to match the substrings use -w option. Just doing out a normal search will show out all the lines.
The following example is the regular grep where it is searching for “is”. When you search for “is”, without any option it will show out “is”, “his”, “this” and everything which has the substring “is”.
$ grep -i "is" demo_file
THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE.
this line is the 1st lower case line in this file.
This Line Has All Its First Character Of The Word With Upper Case.
Two lines above this line is empty.
And this is the last line.
The following example is the WORD grep where it is searching only for the word “is”. Please note that this output does not contain the line “This Line Has All Its First Character Of The Word With Upper Case”, even though “is” is there in the “This”, as the following is looking only for the word “is” and not for “this”.
$ grep -iw "is" demo_file
THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE.
this line is the 1st lower case line in this file.
Two lines above this line is empty.
And this is the last line.
6. Highlighting the search using GREP_OPTIONS
As grep prints out lines from the file by the pattern / string you had given, if you wanted it to highlight which part matches the line, then you need to follow the following way.
When you do the following export you will get the highlighting of the matched searches. In the following example, it will highlight all the this when you set the GREP_OPTIONS environment variable as shown below.
$ export GREP_OPTIONS='--color=auto' GREP_COLOR='100;8'
$ grep this demo_file
this line is the 1st lower case line in this file.
Two lines above this line is empty.
And this is the last line.
7. Searching in all files recursively using grep -r
When you want to search in all the files under the current directory and its sub directory. -r option is the one which you need to use. The following example will look for the string “ramesh” in all the files in the current directory and all it’s subdirectory.
$ grep -r "ramesh" *
8. Invert match using grep -v
You had different options to show the lines matched, to show the lines before match, and to show the lines after match, and to highlight match. So definitely You’d also want the option -v to do invert match.
When you want to display the lines which does not matches the given string/pattern, use the option -v as shown below. This example will display all the lines that did not match the word “go”.
9. Counting the number of matches using grep -c
When you want to count that how many lines matches the given pattern/string, then use the option -c.
Syntax:
$ grep -c "pattern" filename
$ grep -c "go" demo_text
6
When you want do find out how many lines matches the pattern
$ grep -c this demo_file
3
When you want do find out how many lines that does not match the pattern
$ grep -v -c this demo_file
4
Back
The egrep command is more forgiving, it allows you to use some unusual characters in your search, including +,?,|,( and ) . While it's possible to set up grep to search for these characters with the help of the backslash, command can be awkward.
egrep is same as ‘grep -E’ or ‘grep –extended-regex’, which uses extended regular expression.
Syntax:
egrep [options] [regexp] [files]
First create the following employee.txt sample file.
100 Thomas Manager Sales $5,000
200 Jason Developer Technology $5,500
300 Sanjay Sysadmin Technology $7,000
400 Nisha Manager Marketing $9,500
500 Randy DBA Technology $6,000
1. Search for Specific Characters
The following example searches for either J, or N, or R.
$ egrep [JNR] employee.txt
200 Jason Developer Technology $5,500
400 Nisha Manager Marketing $9,500
500 Randy DBA Technology $6,000
2. Search for a Range
The following example searches the range 6-9. i.e It searches for 6, or 7, or 8, or 9.
$ egrep [6-9] employee.txt
300 Sanjay Sysadmin Technology $7,000
400 Nisha Manager Marketing $9,500
500 Randy DBA Technology $6,000
3. egrep OR Example
Pipe symbol is used for egrep OR. The following searches for either Marketing or DBA.
$ egrep 'Marketing|DBA' employee.txt
400 Nisha Manager Marketing $9,500
500 Randy DBA Technology $6,000
Note: egrep supports the extended grep characters: +, ?, |, and ( )
Back
The awk command , named for its developers (Aho, Weinberger, and Kernighan), is more of a database manipulation utility. It can identify lines with a keyword, and read out the text from a specified column in that line.
A common example is with of every user with a listing of "mike".
# awk '/mike/ {print $l}' /etc/passwd
Awk is one of the most powerful tools in Linux used for processing the rows and columns in a file. Awk has built in string functions and associative arrays. Awk supports most of the operators, conditional blocks, and loops available in C language.
By default, awk works on files that have columns of numbers or strings that are separated by white space (tabs or spaces), but the -F option can be used if the columns are separated by another character. awk refers to the first column as $1, the second column as $2, etc. The whole line referred to as $0.
Back
The sed command, short for stream editor, allows you to search for and change specified words or even text streams in a file.
sed is a Stream Editor used for modifying the files in unix (or linux). Whenever you want to make changes to the file automatically, sed comes in handy to do this. Most people never learn its power; they just simply use sed to replace text. You can do many things apart from replacing text with sed. Here I will describe the features of sed with examples.
Consider the below text file as an input.
$ cat file.txt
unix is great os. unix is opensource. unix is free os.
learn operating system.
unixlinux which one you choose.
Sed Command Examples
1. Replacing or substituting string
Sed command is mostly used to replace the text in a file. The below simple sed command replaces the word "unix" with "linux" in the file.
$ sed 's/unix/linux/' file.txt
linux is great os. unix is opensource. unix is free os.
learn operating system.
linuxlinux which one you choose.
Here the "s" specifies the substitution operation. The "/" are delimiters. The "unix" is the search pattern and the "linux" is the replacement string.
By default, the sed command replaces the first occurrence of the pattern in each line and it won't replace the second, third...occurrence in the line.
2. Replacing the nth occurrence of a pattern in a line.
Use the /1, /2 etc flags to replace the first, second occurrence of a pattern in a line. The below command replaces the second occurrence of the word "unix" with "linux" in a line.
$ sed 's/unix/linux/2' file.txt
unix is great os. linux is opensource. unix is free os.
learn operating system.
unixlinux which one you choose.
3. Replacing all the occurrence of the pattern in a line.
The substitute flag /g (global replacement) specifies the sed command to replace all the occurrences of the string in the line.
$ sed 's/unix/linux/g' file.txt
linux is great os. linux is opensource. linux is free os.
learn operating system.
linuxlinux which one you choose.
4. Replacing from nth occurrence to all occurrences in a line.
Use the combination of /1, /2 etc and /g to replace all the patterns from the nth occurrence of a pattern in a line. The following sed command replaces the third, fourth, fifth... "unix" word with "linux" word in a line.
$ sed 's/unix/linux/3g' file.txt
unix is great os. unix is opensource. linux is free os.
learn operating system.
unixlinux which one you choose.
5. Changing the slash (/) delimiter
You can use any delimiter other than the slash. As an example if you want to change the web url to another url as
$ sed 's/http:\/\//www/' file.txt
In this case the url consists the delimiter character which we used. In that case you have to escape the slash with backslash character, otherwise the substitution won't work.
Using too many backslashes makes the sed command look awkward. In this case we can change the delimiter to another character as shown in the below example.
$ sed 's_http://_www_' file.txt
$ sed 's|http://|www|' file.txt
6. Using & as the matched string
There might be cases where you want to search for the pattern and replace that pattern by adding some extra characters to it. In such cases & comes in handy. The & represents the matched string.
$ sed 's/unix/{&}/' file.txt
{unix} is great os. unix is opensource. unix is free os.
learn operating system.
{unix}linux which one you choose.
$ sed 's/unix/{&&}/' file.txt
{unixunix} is great os. unix is opensource. unix is free os.
learn operating system.
{unixunix}linux which one you choose.
7. Using \1,\2 and so on to \9
The first pair of parenthesis specified in the pattern represents the \1, the second represents the \2 and so on. The \1,\2 can be used in the replacement string to make changes to the source string. As an example, if you want to replace the word "unix" in a line with twice as the word like "unixunix" use the sed command as below.
$ sed 's/\(unix\)/\1\1/' file.txt
unixunix is great os. unix is opensource. unix is free os.
learn operating system.
unixunixlinux which one you choose.
The parenthesis needs to be escaped with the backslash character. Another example is if you want to switch the words "unixlinux" as "linuxunix", the sed command is
$ sed 's/\(unix\)\(linux\)/\2\1/' file.txt
unix is great os. unix is opensource. unix is free os.
learn operating system.
linuxunix which one you choose.
Another example is switching the first three characters in a line
$ sed 's/^\(.\)\(.\)\(.\)/\3\2\1/' file.txt
inux is great os. unix is opensource. unix is free os.
aelrn operating system.
inuxlinux which one you choose.
8. Duplicating the replaced line with /p flag
The /p print flag prints the replaced line twice on the terminal. If a line does not have the search pattern and is not replaced, then the /p prints that line only once.
$ sed 's/unix/linux/p' file.txt
linux is great os. unix is opensource. unix is free os.
linux is great os. unix is opensource. unix is free os.
learn operating system.
linuxlinux which one you choose.
linuxlinux which one you choose.
9. Printing only the replaced lines
Use the -n option along with the /p print flag to display only the replaced lines. Here the -n option suppresses the duplicate rows generated by the /p flag and prints the replaced lines only one time.
$ sed -n 's/unix/linux/p' file.txt
linux is great os. unix is opensource. unix is free os.
linuxlinux which one you choose.
If you use -n alone without /p, then the sed does not print anything.
10. Running multiple sed commands.
You can run multiple sed commands by piping the output of one sed command as input to another sed command.
$ sed 's/unix/linux/' file.txt| sed 's/os/system/'
linux is great system. unix is opensource. unix is free os.
learn operating system.
linuxlinux which one you chosysteme.
Sed provides -e option to run multiple sed commands in a single sed command. The above output can be achieved in a single sed command as shown below.
$ sed -e 's/unix/linux/' -e 's/os/system/' file.txt
linux is great system. unix is opensource. unix is free os.
learn operating system.
linuxlinux which one you chosysteme.
11. Replacing string on a specific line number.
You can restrict the sed command to replace the string on a specific line number. An example is
$ sed '3 s/unix/linux/' file.txt
unix is great os. unix is opensource. unix is free os.
learn operating system.
linuxlinux which one you choose.
The above sed command replaces the string only on the third line.
12. Replacing string on a range of lines.
You can specify a range of line numbers to the sed command for replacing a string.
$ sed '1,3 s/unix/linux/' file.txt
linux is great os. unix is opensource. unix is free os.
learn operating system.
linuxlinux which one you choose.
Here the sed command replaces the lines with range from 1 to 3. Another example is
$ sed '2,$ s/unix/linux/' file.txt
linux is great os. unix is opensource. unix is free os.
learn operating system.
linuxlinux which one you choose.
Here $ indicates the last line in the file. So the sed command replaces the text from second line to last line in the file.
13. Replace on a lines which matches a pattern.
You can specify a pattern to the sed command to match in a line. If the pattern match occurs, then only the sed command looks for the string to be replaced and if it finds, then the sed command replaces the string.
$ sed '/linux/ s/unix/centos/' file.txt
unix is great os. unix is opensource. unix is free os.
learn operating system.
centoslinux which one you choose.
Here the sed command first looks for the lines which has the pattern "linux" and then replaces the word "unix" with "centos".
14. Deleting lines.
You can delete the lines a file by specifying the line number or a range or numbers.
$sed '2 d' file.txt
$ sed '5,$ d' file.txt
15. Duplicating lines
You can make the sed command to print each line of a file two times.
$sed 'p' file.txt
16. Sed as grep command
You can make sed command to work as similar to grep command.
$ grep 'unix' file.txt
$ sed -n '/unix/ p' file.txt
Here the sed command looks for the pattern "unix" in each line of a file and prints those lines that has the pattern.
You can also make the sed command to work as grep -v, just by using the reversing the sed with NOT (!).
$ grep -v 'unix' file.txt
$ sed -n '/unix/ !p' file.txt
The ! here inverts the pattern match.
17. Add a line after a match.
The sed command can add a new line after a pattern match is found. The "a" command to sed tells it to add a new line after a match is found.
$ sed '/unix/ a "Add a new line"' file.txt
unix is great os. unix is opensource. unix is free os.
"Add a new line"
learn operating system.
unixlinux which one you choose.
"Add a new line"
18. Add a line before a match
The sed command can add a new line before a pattern match is found. The "i" command to sed tells it to add a new line before a match is found.
$ sed '/unix/ i "Add a new line"' file.txt
"Add a new line"
unix is great os. unix is opensource. unix is free os.
learn operating system.
"Add a new line"
unixlinux which one you choose.
19. Change a line
The sed command can be used to replace an entire line with a new line. The "c" command to sed tells it to change the line.
$ sed '/unix/ c "Change line"' file.txt
"Change line"
learn operating system.
"Change line"
20. Transform like tr command
The sed command can be used to convert the lower case letters to upper case letters by using the transform "y" option.
$ sed 'y/ul/UL/' file.txt
Unix is great os. Unix is opensoUrce. Unix is free os.
Learn operating system.
UnixLinuUx which one yoU choose.
Here the sed command transforms the alphabets "ul" into their uppercase format "UL"
Back
The wc command, short form of word count. can return the number of lines, words, and charcters in a file. The wc options are straightforward .
Syntax :
wc [-c | -m | -C ] [-l] [-w] [ file ... ]
-c Count bytes.
-m Count characters.
-C Same as -m.
-l Count lines.
-w Count words delimited by white space characters or new line characters.
For examples :
$ wc filename
X Y Z filename
X – Number of lines
Y – Number of words
Z – Number of bytes
filename – name of the file
$ wc demofile.txt
36 104 570 demofile.txt
The above output indicates that the demofile.txt has 36 lines, 104 words, and 570 bytes.
Print specific counts as required
You can use -l option to print only the line count as shown below.
$ wc -l demofile.txt
36 demofile.txt
The same way you can use the following options for specific requirements such as,
-w : print only word count
-c : print only the byte count
You can also use any combination of above options.
Print the length of longest line
You can use -L option to print the length of longest line in the file.
$ wc -L demofile.txt
84 demofile.txt
Back
One of the useful option to find the difference between the files is the diff command.
In the simplest case, diff compares the contents of the two files from-file and to-file. A file name of - stands for text read from the standard input. As a special case, diff - - compares a copy of standard input to itself.
If from-file is a directory and to-file is not, diff compares the file in from-file whose file name is that of to-file, and vice versa. The non-directory file must not be -.
If both from-file and to-file are directories, diff compares corresponding files in both directories, in alphabetical order; this comparison is not recursive unless the -r or --recursive option is given.
diff never compares the actual contents of a directory as if it were a file. The file that is fully specified may not be standard input, because standard input is nameless and the notion of ‘‘file with the same name’’ does not apply.
For examples ;
The screenshots provided for these tools shows the difference between the following two empfile1.txt and empfile2.txt.
$ cat empfile1.txt
John Smith 1001 Sr. Engineer
Peter 1002 Engineer
Fernandous 1003 Sr. Engineer
Kraml 1004 Jr. Engineer
$ cat empfile2.txt
John Smith 1001 Sr. Engineer
Peter 1002 Engineer
Fernandous 1003 Resigned
Kraml 1004 Jr. Engineer
Raj 1005 Engineer
1. Diff Command
This is the traditional way to find out the difference two files is using diff command.
$ diff empfile1.txt empfile2.txt
3c3
< Fernandous 1003 Sr. Engineer
---
> Fernandous 1003 Resigned
5c5
<
---
> Raj 1005 Engineer
2. Colordiff Command
3. Wdiff Command
4. Vimdiff Command
Back
You can sort the contents of a file in a number of ways. By default, the sort command sorts the contents in alphabetical order depending on the first letter in each line.Sort command has the capability of sorting numerical values and strings. The sort command can order the lines in a text file.
Syntax :
sort [options] file-name
For example :
The sort /etc/passwd command would sort all users ( including those associated with specific services and such ) by username.
Before practicing the examples create the below two files in your Linux system:
$ cat order.txt
Unix distributed 05 server
Linux virtual 3 server
Unix distributed 05 server
Distributed processing 6 system
$ cat delim_sort.txt
Mayday|4
Janmon|1
Declast|12
1. Sorting lines of text
The default sort command uses alphabetical order (ASCII order) to sort the file. It treats each line as a string and then sorts the lines.
$ sort order.txt
Distributed processing 6 system
Linux virtual 3 server
Unix distributed 05 server
Unix distributed 05 server
2. Sorting based on the field positions.
You can specify the field postions using the -k option of sort command. The sort command uses the space or tab as the default delimiter. To sort based on the data in the second field, run the below command:
$ sort -k2 order.txt
Unix distributed 05 server
Unix distributed 05 server
Distributed processing 6 system
Linux virtual 3 server
You can also specify more than field with k option as a comma separated list. The below command uses the second and fourth fields to sort the data.
$ sort -k2,4 order.txt
3. Numeric sorting
Instead of the default alphabetical sorting order, you can make the sort command to sort in numeric order using the -n option. This is shown below:
$ sort -nk3 order.txt
Linux virtual 3 server
Unix distributed 05 server
Unix distributed 05 server
Distributed processing 6 system
4. Sort in reverse order
By default, the sort command sorts the data in ascending order. You can change this to descending order using the -r option.
$ sort -nrk3 order.txt
Distributed processing 6 system
Unix distributed 05 server
Unix distributed 05 server
Linux virtual 3 server
5. Suppressing duplicates or Print only unique values
You can produce only unique values in the output using the - u option of the sort command.
$ sort -u order.txt
Distributed processing 6 system
Linux virtual 3 server
Unix distributed 05 server
Another way is piping the output of sort command to uniq command.
$ sort order.txt | uniq
6. Delimited file input
In the second, third and fourth examples we have sorted the data based on the field positions. Here the fields are separted by space or tab character. What if the fields are specifed by any other character? In such cases, we have to specify the input delimiter with the -t option. An example is shown below:
$ sort -t'|' -nrk2 delim_sort.txt
Declast|12
Mayday|4
Janmon|1
7. Sorting on months.
We can sort the data in the monthwise using the -M option of the sort command. This is shown below:
$ sort -M delim_sort.txt
Janmon|1
Mayday|4
Declast|12
Treats the first 3 characters in the string as month and then sorts in months order.
Back
Searches with the locate command are almost instantaneous. And locate searches don't require the full file-names. The drawback is that the locate command database is normally updated only once each day, as documented in the /etc/cron.daily/mlocate.cron script of Red Hat Enterprise Linux versions.
The locate command is often the simplest and quickest way to find the locations of files and directories on Linux and other Unix-like operating systems.
As daily jobs are run only once every 24 hours that's not good enough .Fortunately, the noted script can be executed directly from the command line interface, by the root administrator user, Just type in the full path to the file as if it were a command.
# /etc/cron.daily/mlocate.cron
Syntax :
locate [options] name(s)
When used without any options, locate displays every absolute path-name for which the user has access permission that contains any of the names of files and/or directories that are provided to it as arguments (i.e., input data).
The absolute path-name, also referred to as the absolute path or the full path, is the hierarchy of directories from the root directory to the designated file or directory.
The root directory is the directory at the very top of the file-system (i.e., hierarchy of files) that contains all other directories and files on the system and which is designated by a forward slash ( / ).
It is important that the absolute path-name is returned both because it tells the exact locations on the system and because it makes it possible to indicate the locations of files or directories that have the same name but different absolute paths.
For example :
The following would list the absolute paths of all files named file1 and all directories named dir1 for which the user had access permission:
#locate file1 dir1
It would also list any other absolute path-names that contained these strings (i.e., sequences of characters),
For example:
/home/john/file123 or /usr/local/mydir1/index.html.
Back
The find command searches through directories and sub-directories for a desired file.find exits with status 0 if all files are processed successfully, greater than 0 if errors occur.
If you wanted to find the directory with the named.conf, DNS sample configuration file, you could use the following command, which would start the search in the root directory.
#find / -name named.conf
But the speed of that search depends on the memory and processing power available on the local system. With the advent of virtual machines, that processing power may be relatively small.
Alternatively , if you know that this file is located in the /usr/subdirectory tree, you could start in that directory with the following command.
# find /usr -name named.conf
This will find the desired file more quickly.
Examples :
#find -name 'mypage.htm'
In the above command the system would search for any file named mypage.htm in the current directory and any subdirectory.
#find / -name 'mypage.htm'
In the above example the system would search for any file named mypage.htm on the root and all subdirectories from the root.
#find -name 'file*'
In the above example the system would search for any file beginning with file in the current directory and any subdirectory.
#find -name '*' -size +1000k
In the above example the system would search for any file that is larger then 1000k.
#find . -size +500000 -print
Next, similar to the above example, just formatted differently this command would find anything above 500MB.
Back
Sometimes when you may not know the exact name of the file or the exact search item. That is when you can use wildcards and file searches commands ans used to finds one or more files assuming that you know their approximate file-names.
1) find
2) locate
Back
The cmp utility compares two files of any type and writes the results to the standard output. By default, cmp is silent if the files are the same; if they differ, the byte and line number at which the first difference occurred is reported.
Syntax and Options
cmp [OPTION]... FILE1 [FILE2 [SKIP1 [SKIP2]]]
3 cmp Examples :
Two provide examples for this command, lets consider two files :
file1.txt
$ cat file1.txt
Hi My name is Himanshu
file2.txt
$ cat file2.txt
Hi My name is Himanshu Arora
1. Directly compare using cmp
If we straight away try to compare the two files mentioned above, then we see :
$ cmp file1.txt file2.txt
file1.txt file2.txt differ: byte 23, line 1
So we see that cmp utility instantly recognized the difference between contents in two files.
2. Skip same number of initial bytes from both input files
If we want to skip some initial bytes of input files and then start the comparison then -i option can be used
$ cmp -i 5 file1.txt file2.txt
file1.txt file2.txt differ: byte 18, line 1
So we see that the initial 5 bytes were skipped and hence cmp complains that byte 18 differs (which in example 1 was byte 23)
3. Skip different number of initial bytes from both input files
Another case could be when we would want to skip ‘x’ bytes of input in file1 and ‘y’ bytes of input in file2. This could be achieved as follows :
$ cmp -i 5:2 file1.txt file2.txt
file1.txt file2.txt differ: byte 2, line 1
So we see that we can give the option -i with ‘x:y’ kind of input for this case. The output shows that this time the difference occurred very early at the second byte.
Back
A text stream is the movement of data. Linux includes simple commands to help you search , check ,or sort the contents of a file . And there are special files that contain others ,some of these container files are known colloquially as "tarballs".
Tarballs are common way to distribute Linux packages . They are normally distributed in a compressed format, with a .tar.gz or .tgz file extensions, consolidated as a package in a single file.
1) sort
2) diff
3) cmp
4) wc
5) sed
6) awk
7) grep
8) egrep
Back
The most basic command for reading files in Linux is cat command. The cat file-name command scrolls the text within the file-name file.
It also works with multiple file-names ,it concatenates the file-name that you might list as one continuous output to your screen.
You can redirect the output to the file-name of your choice, as described.
The cat command is considered as one of the most frequently used commands on Linux or UNIX like operating systems.
It can be used for the following purposes under UNIX or Linux:
1) Display text files on screen.
2) Copy text files.
3) Combine text files.
4) Create new text files.
Displaying The Contents of Files
To read or read the contents of files, enter:
$ cat /etc/passwd
The above command will display the contents of a file named /etc/passwd. By default cat will send output to the monitor screen.
But, you can redirect from the screen to another command or file using redirection operator as follows:
$ cat /etc/passwd > /tmp/test.txt
Concatenate files
Concatenation means putting multiple file contents together. The original file or files are not modified or deleted. In this example, cat will concatenate copies of the contents of the three files /etc/hosts, /etc/resolv.conf, and /etc/fstab:
$ cat /etc/hosts /etc/resolv.conf /etc/fstab
How Do I Create a File?
You can use cat command for file creation. To create a file called foo.txt, enter:
$ cat > foo.txt
How Do I Copy File?
The cat command can also be used to create a new file and transfer to it the data from an existing file. To make copy of
$ cat oldfile.txt > newfile.txt
Back
Larger files demand a command that can help you scroll through the file text at your leisure. Linux has two of these commands : more and less.
With the more file-name command, you can scroll through the text of a file, from start to finish, one screen at a time. With the less file-name command, you can scroll both directions through the same text with the PAGE UP and PAGE DOWN keys. Both commands support vi style searches.
As the less and more commands do not change files, they are an excellent way to scroll through and search for items in a large text file such an error log.
For example :
To search through the basic /var/log/messages file, ruin the following command.
# less /var/log/messages
Once you have run the command you will be taken to the screen showing the output.
The less command has one more feature as compared to more and cat, it can read text files compressed in Gzip format, normally shown with the .gz extension.
For example :
The man pages associated with many standard commands that are run in the shell can be found in the /usr/share/man/man1 directory.
All of the files in this directory are compressed in .gz format. It can read those file without un-compressing them.
Back
Larger files demand a command that can help you scroll through the file text at your leisure. Linux has two of these commands : more and less.
With the more file-name command, you can scroll through the text of a file, from start to finish, one screen at a time. With the less file-name command, you can scroll both directions through the same text with the PAGE UP and PAGE DOWN keys. Both commands support vi style searches.
As the less and more commands do not change files, they are an excellent way to scroll through and search for items in a large text file such an error log.
For example :
To search through the basic /var/log/messages file, ruin the following command.
# less /var/log/messages
Once you have run the command you will be taken to the screen showing the output.
The less command has one more feature as compared to more and cat, it can read text files compressed in Gzip format, normally shown with the .gz extension.
For example :
The man pages associated with many standard commands that are run in the shell can be found in the /usr/share/man/man1 directory.
All of the files in this directory are compressed in .gz format. It can read those file without un-compressing them.
Back
The head command reads the first few lines of any text given to it as an input and writes them to standard output (which, by default, is the display screen).
Syntax :
head [options] [file(s)]
The square brackets indicate that the enclosed items are optional. By default, head returns the first ten lines of each file name that is provided to it.
For example:
The following will display the first ten lines of the file named aardvark in the current directory (i.e., the directory in which the user is currently working):
$ head aardvark
If it is desired to obtain some number of lines other than the default ten, the -n option can be used followed by an integer indicating the number of lines desired. For example, the above example could be modified to display the first 15 lines from each file:
$ head -n15 aardvark armadillo
head can also return any desired number of bytes (i.e., a sequence of eight bits and usually long enough to represent a single character) from the start of each file rather than a desired number of lines.
This is accomplished using the -c option followed by the number of bytes desired. For example, the following would display the first five bytes of each of the two files provided:
$ head -c 5 aardvark anteater
Back
tail command prints the last N number of lines from given input. By default, it prints last 10 lines of each given file.
Syntax and Options
tail [OPTIONS]… [FILE]…
1. Print the last N lines
To view the last N number of lines from file, just pass the file name with -n option as shown below.
$ tail -n 5 flavours.txt
Debian
Redhat
Gentoo
Fedora core
Note: When you simply pass the filename, it prints out the last 10 lines of the file.
2. Print the appended lines as and when the file grows
You can use -f option to output the appended lines of file instantly as shown below,
$ tail -f /var/log/messages
Note: This is very useful to monitor the log files.
3. Terminate the tail command once PID dies
Using –pid with -f option, you can terminate the tail command when the specific process gets over or killed as shown below.
$ tail -f /tmp/debug.log --pid=2575
In the above tail gets terminated immediately when the pid 2575 vanishes.
4. Keep on trying to tail the file even if it is non-existent
Sometimes, the file intended to tail may not be available when you run the tail command and it may get created later or the files becomes inaccessible .
By this time, you can use the –retry option to keep on trying to open the file as shown below.
$ tail -f /tmp/debug.log --retry
?? tail: warning: --retry is useful mainly when following by name
tail: cannot open `/tmp/log' for reading: No such file or directory ??
After giving the above warnings, it is trying to open the file.
Back
Now ,its time to start reading, copying and moving the files around. Most Linux configuration files are text files. Linux editors are text editors. Linux commands are designed to read text files.
To identify the types of files in the current directory ,try the file * command.
1) cat
2) less
3) more
4) head
5) tail
Back
At the command line interface ,the current directory may be either in the top-level root ( / ) directory or sub-directory .
The pwd command identifies the current directory .
It will give you a directory name relative to the top-level root ( / ) .
With this information in hand ,you can move to different directory if needed .
$ pwd
/home/michael
Back
cd command is used to change the current directory to another directory.
By default ,the cd command will navigates you to your home directory . The ( ~ ) tilde is not required for that.
The syntax is cd followed by the name of the directory you want to go to.
Examples:
1) cd /home/user/www will change the directory you are in to /home/user/www.
2) cd /home/ri*/www would also take you to /home/rich/www, assuming there was no other folder in /home beginning with ri.
3) You can also use ../ to move you up one level in the file structure, or ../../ to move up two levels etc.
4) If you are in /home/rich/www, then cd ../ will take you to /home/rich, and ../../ will take you to /home.
5) From /home/rich/www, cd ../../bob will take you to /home/bob.