Common text tools and grepping

Learn about grepping and common text tools.

head & tail :

head and tail are a great commands to show a specified number of lines, for example if you want to display the last 5 lines from the file /etc/passwd use the command syntax below :

  • tail -5 /etc/passwd

Head will do the same job but instead, it will display the first 5 lines from the file /etc/shadow

  • head -5 /etc/shadow

CAT :

Another nice command to display the content of a file. this command is more useful when you used less | more

  • cat /etc/passwd | more -> to display the content of /etc/passwd

  • tac /etc/passwd | less -> same thing but this time from tail to head.

cut | sort | tr :

these 3 commands makes a great utility. the cut command is used to cut a lines using a delimiter, followed by sort which is used to sort a file in a precise format. while tr is used for translation. lets learn how to use these commands. I will display the first field from /etc/passwd in upper cases and sort it reversely.

cut -f1 -d: /etc/passwd | sort -r | tr [:lower:] [:upper:]

the output of this command :

Below you will find a summary for the most common options for cut and sort :

  • Starting with cut :

    -b : bytes -c : character -f : field -d : delimiter

  • Moving to the sort command : -r : reverse -d : dictionary order -n : numerical value -R : Random -b : ignore blanks -o : specify output file

Another great command you can use with sort, is unique

consult man unique for more informations.

sed and awk :

sed and awk are both powerful commands. sed (stream editor) used for filtering and transforming text. let me explain using some examples.

  • sed -i 's/oldtext/new_text/g' <filename> -> this command will change the old_text to new text in <filename> , the '-i' option is used to ensure the changes in the <filename>, s refers to substitute while g refers to global.

  • sed -i '1d' <filename> -> deleting the first line from <filename>

awk is a very advanced command, is a pattern scanning and processing language. let me make it simple for you by using this command :

  • gawk -F: '{ print $1 }' /etc/passwd -> print the first field from /etc/passwd. the "-F" option refers to field.

Grep :

grep is the most common command in unix, it is used to filtering while looking deeply in a file text. below you will find a summary for the most commin options for grep.

  • -R : recursive -v : not containing "text" -i : ignore case -f : specify file -l : list the containing files names -L : list the files names without match -A <n> : print n lines after -B <n> : print n lines before -C <n> : print n lines before & after

Last updated

Was this helpful?