Loading...
Basic Linux

String Processing Commands

Regular Expressions or Regex (Grep):

Globally research a regular expression and print.
To search a string or regular expression in a file(s)
Syntax:

grep  [options]  PATTERN FILE(S)
grep        [options]       word to search         filename

Examples:

$grep  john  filename
$grep   "it  technology"   filename
$grep  john   filename1   filename2   filename3

Search all files in a current directory

$grep   john   *

Ignore case

$grep   -i   john   filename

Counts number of lines.

$grep  -c   john    filename

Print the lines along with line numbers

$grep   -n   john   filename

List file names only the given pattern

$grep   -l   john    filename

Search the pattern recursively

$grep   -r john   *

Prints non matching lines

$grep   -v    john   filename

Prints only the given pattern

$grep    -o   john   filename

Prints start with exam pattern

$grep   "exam*"  filename 
$grep   "b[a e i o u]ll"  filename

Output:
ball
bell
bill
boll

$grep   "b..d"   filename

Output:
band
book
ba#h
ba-d

Note:
” . ” & ” * ” are wild card characters, it matches any single character.

Awk

Awk is used to search a word or particular string in a file. To Know more about AWK and how it get used see below examples.

The syntax of AWK:

To print the second line:

awk ‘FNR == 2 {print}’

To print the second field:

awk ‘{print $2}’

To print the third field of the fifth line:

awk ‘FNR == 5 {print $3}’

If you wish to list all the lines and columns in a file, execute
Copy$ awk ‘ {print $0}’ file.txt

To match all entries with the letter ā€˜eā€™
awk ‘/e/ {print $0}’ file.txt

To print the 2nd and 3rd columns, execute the command below.

$ awk ‘{print $2 “\t” $3}’ file.txt

$ awk ‘/variable_to_be_matched/ {print $0}’ file.txt

Use exit to stop as soon as you’ve printed the required output, there’s no use to process the whole file:

awk ‘FNR == 2 {print; exit}’

Leave a Reply

Your email address will not be published. Required fields are marked *