sâmbătă, 27 aprilie 2013

Programarea server in PHP


Programare server in PHP





Acest tutorial prezinta PHP, un limbaj de generare de scripturi, cu sursa deschisa utilizat pe un numar foarte mare de servere Web din intreaga lume.

Prezentare PHP

Similar Limbajului JavaScript, PHP este compus din comenzi ce pot fi inglobate in codul HTML al paginilor Web, insa acesta este un limbaj de programare pe parte de server. Vom incerca sa oferim o introducere in PHP pentru cei care nu l-au intalnit niciodata si o recapitulare a elementelor de baza pentru cei care il cunosc.

Inglobarea PHP in paginile HTML

Instructiunile PHP sun inglobate in documentele HTML plasandu-le intre etichetele <?php si ?>. Orice se gaseste intre aceste etichete este evaluat de serverul Web si inlocuit cu codul HTML corespunzator, inaite ca pagina respectiva sa fie servita browserului.

Obtinerea datelor de iesire HTML din PHP

Mai multe comenzi PHP va ajuta sa scrieti si cod HTML direct din pagina. Cea mai simpla comanda este echo:

echo “ aceasta linie este scrisa cu PHP”;

Afisarea mesajului “Salut PHP!”


<html>
<head>
<title>Un simplu script PHP</title>
</head>
<body>
<?php echo “<h1>Salut PHP!</h1>”; ?>
</body>
</html>


Variabilele in PHP

Variabilele in PHP sunt numite containere in care sunt stocate elemente de date. Toate numele de variabile trebuie sa inceapa cu caracterul ”$” urmat de un sir de litere, cifre si liniute de subliniere.
Putem atribui valori variabilelor fara a le declara mai intai:
$score = 71;
$player = ‘Harry Scott’;

Rezumat

Acest  tutorial a prezentat principiile programarii in PHP.

 Bibliografie

Phil Ballard “Ajax in lectii de 10 minute”, Ed. Teora, 2008.

Document Link: https://docs.google.com/document/d/1KUpSA2msofBZWCQ0wcQbaK0WU8TNk2J1GSVZNoPr4Q0/pub

Programare cu JavaScript

In acest tutorial vom introduce conceptul de generare de scripturi pe partea de client prin intermediul limbajului JavaScript. Scripturile pe partea de client sunt inglobate in paginile Web si executate de un interpretor JavaScript incorporat in browser. Ele adauga functionalitate suplimentara unei pagini HTML, care altfel ar fi statica.
JavaScript a fost creat de firma Netscape.

Folosind JavaScript puteti adauga functionalitati suplimentare in paginile dumneavoastra Web, de exemplu:

  • schimbarea modului in care sunt afisate elementele paginii;
  • adaugarea animatiei si a altor efecte de imagine;
  • deschiderea ferestrelor si casetelor de dialog pop-up;
  • verificarea datelor introduse de utilizator.
In momentul de fata toate browserele moderne accepta JavaScript.

Elementele de baza JavaScript

Comenzile JavaScript pot fi inglobate direct in paginile HTML, plasandule intre etichetele 
<script> 
......aici plasati codul JavaScript!
</script>
De asemenea se mai  obisnuieste ca functuiile JavaScript sa se pastreze in fisiere separate cu extensia .js si apoi legate de fisierele HTML, prin introducerea in antetul fisierului HTML a unei linii similare cu cea de mai jos:
<SCRIPT language="JavaScript" SRC="myJS.js"></SCRIPT>
Aceasta linie va permite sa apelati orice functie JavaScript din fisierul myJS.js ca si cum codul sursa a fost scris direct in pagina Web.

Adaugarea codului JavaScript

Sa trecem la treaba si sa adaugam o comanda JavaScript la aceasta pagina Web, sa spunem afisarea datei curente:

<script>
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>

Acum sa adaugam si codul in HTML :

<h1>My First JavaScript</h1>
<p id="demo">This is a paragraph.</p>
<button type="button" onclick="displayDate()">Display Date</button>
Aici aveti aplicatia executata in browser:

My First JavaScript

This is a paragraph.


Includerea codului JavaScript in paginile HTML

In paginile noastre Web putem include oricat de multe perechi de etichete <script>....</script>  avem nevoie. Insa, trebuie sa fim atenti unde le plasam in document. Comenzile JavaScript sunt executate in ordinea in care apar in pagina. Codul JS poate fi adaugat si in sectiunea de antet a paginii HTML.

Manageri de eveniment

Deseori, veti dori executarea codului JS ca urmare a aparitiei unui anumit eveniment. De exemplu, intr-un formular HTML, ati putea decide ca JS sa verifice validitatea datelor intoduse de utilizator, in alte situatii, veti dori sa alertati utilizatorul prin deschiderea unei casete de mesaj ori de cate ori se executa click pe un anumit buton.

Pentru a obtine aceste efecte, veti utiliza interfete speciale furnizate de catre browser si cunoscute sub numele de manageri de eveniment. Acestia va permit sa apelati automat JS cand au loc anumite tipuri de evenimente. Fie codul:
<form>
<input type="button" value="Apasa aici" onClick="alert('Ati apasat butonul!')">
</form>
In browser:



Capturam actiunea prin care utilizatorul executa clic pe buton, folosind managerul de evenimente onClick. Cand este detectata executarea clicului de catre utilizator, scriptul executa instructiunile prezente in atributul onClick al etichetei input:

onClick="alert('Ati apasatButonul!')"
Crearea functiilor

In cele mai multe cazuri, va trebui sa combinati diferite metode si obiecte JS, folosind probabil mai multe linii de cod. JS va permite sa compuneti astfel de blocuri de instructiuni si sa le denumiti, facilitand astfel scrierea, intelegerea si mentinerea codului.

In randurile urmatoare sa folosim un alt manager de eveniment, insa de aceasta data il vom folosi pentru a apela o functie, si nu pentru a apela direct o metoda JS. Iata codul pentru functia noastra:
<script language ="JavaScript">
   function showAlert() {
        alert("Este o imagine!")
  }
</script>
Mai departe dorim ca aceasta caseta de dialog cu mesaj de avertizare sa apara cand indicatorul mouse-ului utilizatorului trece peste fotografia din pagina noastra. Prin urmare adaugam un atribut in eticheta <img> care contine imaginea, astfel:
<img src="cathdral.jpg" border="2" onMouseOver="showAlert()" alt="Cathedral"/>
Aceasta linie foloseste managerul de evenimente onMouseOver pentru a detecta momentul in care cursorul intra in zona ocupata de fotografia de pe ecran. Puteti verifica acest lucru trecand cursorul deasupra imaginii de la inceput.

Trecerea argumentelor catre functii

Putem foarte usor sa apelam functia noastra printr-o gama foarte larga de manageri de eveniment pentru a deschide o caseta de avertizare. Din pacate mesajul avertismentului va afisa intotdeauna acelasi text.

Insa daca putem indica functiei mesajul ce trebuie afisat, asa incat sa avem mesaje de avertizare diferite pentru situatii diferite. Putem obtine acest lucru foarte simplu trecand mesajul catre functie ca un argument:
<script language="JavaScript" type="text/javascript" >
function showAlert(message) {
alert(message)
}
</script>

Functia se asteapta acum sa gaseasca textul mesajului definit, trecut ca argument in cadrul apelarii. Se rescrie codurile di HTML:
<img src="cathedral.jpg" border="2" onMouseOver="showAlert('Aceasta este o imagine!')" alt="cathedral" />

De asemenea vom rescrie si codul din onClick:
<input type="button" value="Apasa aici" onClick="showAlert('Ai apasat butonul!')" /> 
Alti manageri de eveniment 


  • onChange - apare cand se modifica valoarea dintr-un camp de introducere a datelor.
  • onClick - apare cand utilizatorul executa click cu mouse-ul pe respectivul element.
  • onLoad - apare la terminarea incarcarii paginii.
  • onMouseOver - cursorul intra in zona de ecran ocupata de elementul respectiv.
  • onMouseOut - cand o paraseste.
  • onSubmit - apare in momentul cand este transmis un formular.
Manipularea datelor in JavaScript 

Java Script ofera posibilitatea de a defini si utiliza variabile si vectori, de a lucra aritmetic cu date calendaristice si ore si de a controla fluxul programului cu cicluri si ramuri conditionale.

Variabile

Conceptul de variabila probabil ca va este familiar daca ati vreodata algebra sau ati programat intr-un libaj oarecare. O variabila este o informatie  careia i s-a dat un nume la care se poate face usor referire. In JS variabilele se declara folosind cuvantul var.

var speed = 63;

Validarea Formularelor

Dorim sa capturam evenimentul prin care utilizatorul incearca sa transmita formularul si sa folosim acest eveniment pentru a declansa functia noastra JS care verifica validitatea datelor. Codul HTML este:


<form name="form1" method="post" action="otherpage.html">
Introduceti un numar de la 1 la 10: <input size="4" type="text" name="usernumber">
<input type="submit" value="Enter" onSubmit="return numcheck()">
</form>
Acum  vom scrie functia:
<script language="JavaScript" type="text/javascript">
function numcheck() {
var numentered = document.form1.usernumber.value;
if((numentered>=1)&&(numentered<=10)) {
return true;
} else {
alert("Datele introduse sunt incorecte. Incercati din nou");
return false;
}
}
</script>
Introduceti un numar de la 1 la 10:

Rezumat

Acest Tutorial a prezentat elementele de baza ale programarii in JavaScript.
  Bibliografie

http://www.mybloggerlab.com/2012/04/insert-html-css-javascript-codes-in.html
http://www.w3schools.com/js/default.asp

vineri, 26 aprilie 2013

SimplyMEPIS 11.0

SimplyMEPIS 
Distributia SimplyMEPIS(bazata pe Debian) a atras atentia pentru simplu fapt ca incearca sa aduca in prim plan ceea ce este cu adevarat important la un sistem de operare - performanta, avand in vedere atat viteza de functionare cat si stabilitatea.

Combinatia de software este suficienta pentru a oferi un sistem de operare dotat cu cele mai noi versiuni ale aplicatiilor principale. Editarea documentelor este facilitata de prezenta OpenOffice.org.

Site oficial: http://www.mepis.org/discover-mepis .



Pinta - editor foto multiplatforma

Pinta 1.4 este un software gratuit, open source si are ca baza de inspiratie Paint.NET.


Website http://pinta-project.com/
Source code https://github.com/PintaProject
Libaj de programare C#

Scopul acestuia  este de a oferi utilizatorului unelte simple dar puternice pentru a manipula si edita imagini pe sitemele de operare Linux, Mac si Windows.

Foto prelucrata in Pinta.
Din Ubuntu Software Center pudteti instala aceasta aplicatie sau utilizand in terminal comanda:
sudo apt-get install pinta .

Este un editor foto mai simplu decat GIMP, si mult mai intuitiv. Cu Pinta puteti aplica rapid schimbari pe imaginile de pe harddisc, le puteti taia, aplica degrade-uri si interveni cu actiuni de sip spray.

Cariere Android


Brands are rushing ahead at breakneck speed to build their apps on the Android OS, and that trend has opened up enormous job opportunities in the Android domain.  
According to a leading IT job site, www.dice.com, job openings for Android developers soared by 50 per cent in early 2012. In the wake of the increasing rush for proficient developers, a plethora of IT training institutes across the country are launching special curriculum and conducting classes for Android application development. So if you wish to take this unexplored yet promising career option, you can hone your creative skills in a good institute.
Android development: A big career boost!
Neeraj Kumar, director, Tech Mentro, Noida, says, The Android OS is literally flexing its muscles in the mobile domain and it won’t be wrong to say that jobs for Android application development may even surpass the Apple market. The Android applications platform promises vast job potential in the current IT field. This is not just confined to the mobile application development, but also has scope in hardware solutions like Android customisation or optimisation, device drivers, etc.
Echoing similar views, Vikram C, founder of InfoWinder Training Academy, Jaipur, says, Android development as a career segment is the next big thing in the job industry. The job market for Android programming is gaining momentum at an amazing pace. Moreover, there is a dearth of talent in this much-talked about field and, soon, major companies will make a beeline for good Android development professionals. So, for those who are planning to make a career in this uncharted arena, getting enrolled in a good training institute will serve the purpose and help them gather the requisite skills.
Why are training institutes important?  
At a time when online tutorials are the order of the day, why would anyone opt to enroll in a training institute for Android programming? Ramesh Kumar, director, Linux Learning Centre Pvt Ltd, Bangalore, quips, Training institutes help you have a wider view of the whole process. The live training experience helps you exercise your creative skills practically, which is essentially required to gain proficiency in Android programming. Since Android application development is a new domain, classroom training makes it a holistic experience for all those who want to acquire the know-how about the subject.
The skills in demand
While most Android applications are written in Java, an adept Android professional should have the basic knowledge of Java, HTML and other general technical skills, says Madeeswer Gandhi V, managing director, IgniteMindz, Chennai. Developers who know the principles of object-oriented programming and understand user interface will have an advantage over others. But getting trained in a good institute will definitely help them cope with the requirements of the job market. A proficient programmer should be able to juggle between languages effortlessly, since Android apps development essentially needs learning a new syntax. Innovative thinking to work on the differing needs of the consumers will spell success for an Android programmer and this is possible once you get good training, says Gandhi.
The moolah factor
So, what is the average remuneration that an Android developer can expect? The average salary starts from Rs 15,000-Rs 18,000 per month, depending on the expertise, experience and the position of the individual. The rapid growth of the Android market will soon see companies fighting it big to hire more talented developers and this will, in turn, give way to higher remuneration, says Tarun Acharya, managing director, Linux Lab, Pune. And what are the basic fees to get enrolled in a training institute? For beginners, it ranges between Rs 12,000 to Rs 14,000, and the course duration is generally four weeks,  adds Acharya.
Handy tips
While building a career as an Android apps developer seems to be the next big thing, what are the tips experts can give to beginners in this industry? When you develop a personalised app, publish it on the cloud-based Google Play (earlier known as Android Market). Keep a provision so that even others can use and benefit from it. You can also quote a price for it. Once your apps become popular, money will automatically flow, says Ballabrao Vasu, chief technical officer, EasyARM, Bengaluru.

Sursa(http://www.linuxforu.com/2013/04/android-apps-development-a-hot-career-option/).

joi, 25 aprilie 2013

UBUNTU 13.04 a fost lansat

Potrivit dezvoltatorului, Ubuntu Raring Ringtail "este cea mai rapida si mai finisata din punct de vedere estetic versiune de Ubuntu". Canonical s-a concentrat de aceasta data pentru Ubuntu 13.04 pe un consum mult mai mic de memorie si pe optimizare fata de versiunile anterioare.


Cei de la Canonical si-au concetrat atentia si asupra dezvoltarii versiunii mobile a Ubuntu, astfel ca userii vor gasi in imaginea sistemului de operare si SDK-ul pentru device-uri portabile.
Extrem de important este faptul ca, spre deosebire Windows (Windows 8 vs. RT), Ubuntu Mobile va fi similar din toate punctele de vedere cu Ubuntu Desktop si va rula pe o gama foarte variata de masini, de la desktop la mobile.

Platforma de e-learning - Moodle

Moodle este o platformă de învățare (e-learning) dezvoltată inițial de Martin Dougiamas pentru a ajuta profesorii să creeze cursuri online care să fie focusate pe interacțiune și construirea colaborativă a conținutului educațional, care este în continuă dezvoltare.


Moodle (abrevierea de la englezescul Modular Object-Oriented Dynamic Learning Environment) este un software liber și Open source de învățare, cunoscut de asemenea și ca un Sistem de Management al Cursului, Sistem de Management al Învățării sau ca un Spațiu de Învățare Virtual.


Proiectul Moodle comprimă câteva elemente distincte dar care se află într-o legătură, precum:
  • Software-ul Moodle.
  • Moodle Pty Ltd (cunoscută de asemenea și ca Sediul Moodle sau Trustul Moodle, cu sediul în PerthAustralia de Vest), o companie Australiană care efectuează majoritatea dezvoltării nucelului platformei Moodle.
  • Comunitatea Moodle, o rețea liberă cu peste un milion de utilizatori înregistrați care interacționează prin intermediul comunității site-ului Moodle pentru a împărtăși idei, coduri, informații și suport gratuit. Acestă comunitate include de asemenea un număr mare de dezvoltatori, care datorită licenței de tip open source (sursă deschisă) și designului modular, pot să creeze module suplimentare și funcționalități. Asta a permis ca Moodle să devină un adevărat proiect global de colaborare în domeniul de aplicare.
  • Rețeaua partenerilor Moodle, care formează partea comercială al mediului Moodle și care asigură cea mai mare parte din bani pentru finanțarea Moodle Pty Ltd.

Moodle are mai multe caracteristici considerate tipice pentru o platformă educațională plus ceva inovații originale (cum ar fi sistemul său de filtrare). Moodle este foarte asemănător cu un sistem de management al învățării. Moodle poate fi utilizat în multe tipuri de medii ca de exemplu: în mediul educațional, pentru formare și dezvoltare, în mediul afacerilor.
Dezvoltatorii pot extinde construcția modulară al platformei Moodle prin crearea de noi plugin-uri care au funcții specifice. Infrastructura Moodle suportă multe tipuri de plugin-uri:
  • activități (inclusiv jocuri de cuvinte și de numere)
  • tipuri de resurse
  • tipuri de întrebări (cu răspunsuri multiple, adevărat sau fals, „completați spațiul liber”)
  • teme grafice
  • metode de autentificare (poate solicita nume de utilizator și parolă de acces)
  • metode de înscriere
  • filtre de conținut
Multe plugin-uri ale terțelor sunt disponibile gratuit și se folosesc de această infrastructură.

Website Romania(http://www.moodle.ro/).

Gimp 2.8 - un editor foto profesional gratuit

GIMP este un program multi-platformă pentru editarea de imagini (sau grafică) de tip raster (sau bitmap). GIMP este acronim pentru GNU Image Manipulation Program (în română program GNU pentru manipularea unei imagini), fiind destinat executării diverselor modificări cum ar fi retușarea fotografiilor, a compoziției imaginii sau construcția imaginilor.


Studenți fiind, Peter Mattis și Spencer Kimball au început să lucreze la GIMP în anul 1995 și au publicat varianta beta în februarie 1996. Varianta beta s-a bazat pe Motif, un instrument de construire a intefețelor grafice. Deoarece acest instrument necesita o licență, cei doi au creat o alternativă open source, denumită GTK.

În primăvara anului 1997 cei doi au absolvit facultatea și au abandonat în mare măsură proiectul GIMP. După o vreme mai mulți voluntari au recuperat codurile și au revitalizat proiectul GIMP. În etapa inițială, programul se numea General Image Manipulation Program, dar ulterior litera G din acronim a fost folosită spre a arăta că este licențiat sub licența GNU GPL.

Cea mai recentă versiune stabilă este GIMP 2.8, din care există și o variantă portabilă pentru memorie flash USB.

marți, 23 aprilie 2013

A Beginner’s Guide to Grep: Basics and Regular Expressions

Grep me out!
Grep is one among the system administrator’s “Swiss Army knife” set of tools, and is extremely useful to search for strings and patterns in a group of files, or even sub-folders. This article introduces the basics of Grep, provides examples of advanced use and links you to further reading.
Grep (an acronym for “Global Regular Expression Print”) is installed by default on almost every distribution of Linux, BSD and UNIX, and is even available for Windows. GNU and the Free Software Foundation distribute Grep as part of their suite of open source tools. This tutorial focuses primarily on this GNU version, as it is currently the most widely used.
Grep finds a string in a given file or input, quickly and efficiently. While most everyday uses of the command are simple, there are a variety of more advanced uses that most people don’t know about — including regular expressions and more, which can become quite complicated.
The tool has its roots in an extended regular expression syntax that was added to UNIX after Ken Thompson’s original regular expression implementation. The latter searches for any of a list of fixed strings, using the Aho-Corasick algorithm. These variants are embodied in most modern Grep implementations as command-line switches (and standardised as -E and -F in POSIX.2). In such combined implementations, Grep may also behave differently depending on the name by which it is invoked, allowing fGrep, eGrep, and Grep to be links to the same program.
There are two ways to provide input to Grep, each with its own particular uses. First, Grep can be used to search a given file or files on a system (including a recursive search through sub-folders). Grep also accepts inputs (usually via a pipe) from another command or series of commands.

Regular expressions

A regular expression, often shortened to “regex” or “regexp”, is a way of specifying a pattern (a particular set of characters or words) in text that can be applied to variable inputs to find all occurrences that match the pattern. Regexes enhance the ability to meaningfully process text content, especially when combined with other commands.
Usually, regular expressions are included in the Grep command in the following format:
grep [options] [regexp] [filename]
GNU Grep uses the GNU version of regular expressions, which is very similar (but not identical) to POSIX regular expressions. In fact, most varieties of regular expressions are quite similar, but have differences in escapes, meta-characters, or special operators.
GNU Grep has two regular expression feature sets: Basic and Extended. In basic regular expressions, the meta-characters ?+{|(, and ) lose their special meaning (whose uses are described later in this article). As mentioned below, to switch to using extended regular expressions, you need to add the option -E to the grep command.
It is customary to enclose the regular expression in single quotation marks, to prevent the shell (Bash or others) from trying to interpret and expand the expression before launching the grepprocess. For example, if a pair of back-ticks in the regexp is not quoted, it would result in the text between the back-ticks being executed as a Bash sub-process — and if this happens to be a valid command, the text returned by it takes the regular expression’s place in the command-line parameters given to Grep! Not at all what we want.
Again, due to shell behaviour, you can also enclose the regex in double quotes — in this case, you can use environment variables in the regex, and the shell will substitute them before calling Grep. This can be very useful, depending on what you’re trying to do — or it could turn out to be a nuisance. Remember the difference in behaviour.

Basic usage

Now let’s go on to some practical examples of using Grep. To better understand the results, I’ve created a simple text file on which we will run our Grep searches; the file contains the following lines:
Hi
this
is test file
to carry out few regular expressions
practical with grep
123 456
Abcd
ABCD
Case-insensitive search (grep -i):
[manish@clone ~]$ grep -i 'abcd' testfile
Abcd
ABCD
As you can see, the -i flag causes a search for “abcd” to return matches that have different cases for the characters from what the search string does.
Whole-word search (grep -w):
[manish@clone ~]$ grep -w 'test' testfile
is test file
This type of search only returns lines where the sought-for string is a whole word and not part of a larger word.
Recursively search through sub-folders (grep -r <pattern> <path>):
[manish@clone ~]$ grep -r '456' /root/
/root/testfile:Year is 2010
Inverted search (grep -v):
[manish@clone ~]$ grep -v 'practical' testfile
Hi
this
is test file
to carry out few regular expressions
123 456
Abcd
ABCD
This prints all the lines in the file, except the line that contains the word “practical”.
An interesting relative is the -L flag (you can also use --files-without-match), which outputs the names of files that do NOT contain matches for your search pattern. The matches for your search pattern are not themselves printed, only the names are.
[manish@clone ~]$ grep -r -L "Network" /var/log/*
/var/log/anaconda.log
/var/log/anaconda.syslog
/var/log/audit/audit.log
/var/log/boot.log
/var/log/boot.log.1
...
The “opposite” flag to -L is -l or --files-with-matches, which prints out (only) the names of files that do contain matches for your search pattern.
Print additional (trailing) context lines after match (grep -A <NUM>):
[manish@clone ~]$ grep -A1 '123'  testfile
123 456
Abcd
For each line that matches the search, Grep prints the matching line, as well as the next one line after the match. Varying the number provided to -A changes the number of additional lines that are in the output.
Print additional (leading) context lines before match (grep -B <NUM>):
[manish@clone ~]$ grep -B2 'Abcd' testfile
practical with grep
123 456
Abcd
Print additional (leading and trailing) context lines before and after the match (grep -C <NUM>):
[manish@clone ~]$ grep -C2 'carry' testfile
this
is test file
to carry out few regular expressions
practical with grep
123 456
As you can see, this has printed out two lines before and after the single match found in the file; if there are multiple matches, Grep inserts a line containing -- between each group of lines (each match and its context lines).
Print the filename for each match (grep -H <pattern> filename):
[manish@clone ~]$ grep -H 'a' testfile
testfile:to carry out few regular expressions
testfile:practical with grep
Now, let’s run the search a bit differently:
[manish@clone ~]$ cat testfile | grep -H 'a'
(standard input):to carry out few regular expressions
(standard input):practical with grep
When the stream that Grep is asked to search is passed to its standard input via a pipe from a previous command in the chain, grep -H displays (standard input) as the filename.
Run in “quiet” mode (grep -q): When run with this flag, Grep does not write anything to standard output, but sets its return value (also known as exit status) to reflect whether a match was found or not. This option is mainly used in scripts that need to check if a given file contains a particular match. A return status of 0 (zero) indicates that a match was found; 1 indicates that no match was found.
[manish@clone ~]$ grep -q '2010' testfile
[manish@clone ~]$ echo $?
1
[manish@clone ~]$ grep -q '456' testfile
[manish@clone ~]$ echo $?
0

Using regular expressions

[manish@clone ~]$ grep 'c.r' testfile
to carry out few regular expressions
In the search above, . is used to match any single character — which is why it matches “car” in “carry”. Grep has a powerful regular expression matching engine, which we can’t hope to cover in depth here, but we will include a few important points:
  • •Most characters, including all letters and digits, are actually regular expressions that match themselves.
  • •Any meta-character (with special meaning to Grep, like the . in the example above) may be quoted by preceding it with a backslash. This makes Grep treat it as an ordinary character.
[manish@clone ~]$ grep 'c\.r' testfile
[manish@clone ~]$
As you can see, preceding . with a backslash has removed its significance as a meta-character.
A regular expression may be followed by one of several repetition operators:
  • The period (.) matches any single character.
  • ? means that the preceding item is optional, and if found, will be matched at the most, once.
  • * means that the preceding item will be matched zero or more times.
  • + means the preceding item will be matched one or more times.
  • {n} means the preceding item is matched exactly n times, while {n,} means the item is matched n or more times. {n,m} means that the preceding item is matched at least n times, but not more than m times. {,m} means that the preceding item is matched, at the most, mtimes.
However, the repetition operators are part of GNU Grep’s extended regular expression syntax, so to use these effectively, remember to add the -E option to your command.
Read this tutorial for an introduction to more of Grep regular expression features. For more information on regular expression syntax, refer to the Regular Expressions chapter in the Grep manual. Meanwhile, we will present some examples of regular expressions and try to show how they work.

Character classes in regular expressions

The “character class” tool is one of the more flexible and often-used features of regular expressions. There are two basic ways to use character classes: to specify a list of characters (for example, [aeiou] is a list of vowel characters), or a range (like [m-t], which expands to[mnopqrst]). Ranges are a convenience that saves having to type an entire sequence of characters. A character class can also include a list of special characters, but they can’t be used as a range.
A single character class instance will match only one character; to match multiple occurrences of the class, you would need to add a repetition operator, like those mentioned above. For example, to find an eleven-letter string comprising only lower-case alphabets, the regex would be: [a-z]{11}. As mentioned earlier, to use the repetition operators, we need to add the option-E. Let’s run this on our test file:
[manish@clone ~]$ Grep -E '[a-z]{11}' testfile
to carry out few regular expressions
Here, “expressions” is the only all-lowercase 11-character string in the file; so this is the only line printed as the output.
There are quite a few character classes that are very commonly used in regular expressions, and these are provided as named classes. For example, the [a-z] class of lower-case alphabets that we used above, has the named class [:lower:]. Naturally, [:upper:] is upper-case letters A to Z, and [:alpha:] is all alphabetic characters, equivalent to [:lower:] plus[:upper:][:digit:] is the digits 0 to 9, and [:alnum:] is alphanumeric characters — a combination of [:alpha:] and [:digit:]. The Grep manual lists out more of these named classes.
When a carat (^) is used as the first character in a character class, it is a negation of the class, effectively meaning, “none of these characters”.

Line and word anchors

The ^ anchor specifies that the pattern following it should be at the start of the line:
[manish@clone ~]$ grep '^th' testfile
this
The $ anchor specifies that the pattern before it should be at the end of the line.
[manish@clone ~]$ grep 'i$' testfile
Hi
The operator \< anchors the pattern to the start of a word.
[manish@clone ~]$ grep '\<fe' testfile
to carry out few regular expressions
Similarly, \> anchors the pattern to the end of a word.
[manish@clone ~]$ grep 'le\>' testfile
is test file
The \b (word boundary) anchor can be used in place of \< and \> to signify the beginning or end of a word:
[manish@clone ~]$ grep -e '\breg' testfile
to carry out few regular expressions
Finally, we look at the | (alternation) operator, which is part of the extended regex features. A pattern containing this operator separately matches the parts on either side of it; if either one is found, the line containing it is a match. The parts can themselves be complex regular expressions, so this means you can check each line in a file for multiple search patterns in one pass.
[manish@clone ~]$ grep -E 'hi|bc' testfile
this
Abcd
That was pretty simple; so let’s try a more complicated one. Can you reason out why the output lines for this regex are as shown below?
[manish@clone ~]$ grep -E '^[t-z]+|[^a-z]+$' testfile
this
to carry out few regular expressions
123 456
ABCD

Using shell expansions in the pattern input to Grep

As mentioned earlier, if you don’t single-quote the pattern passed to Grep, the shell could perform shell expansion on the pattern and actually feed a changed pattern to Grep. This can also be done intentionally, when you need it — let’s look at a few examples.
[root@clone ~]# grep "$HOME" /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
Here, we intentionally use double quotes to make the Bash shell replace the environment variable $HOME with the actual value of the variable (in this case, /root). Thus, Grep searches the /etc/passwd file for the text /root, yielding the two lines that match.
[root@clone ~]# grep `whoami` /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
Here, back-tick expansion is done by the shell, replacing `whoami` with the user name (root) that is returned by the whoami command.
Well, we hope this has set you on your way to using this very efficient tool.