DEV Community

Josh
Josh

Posted on

Text Processing & Regular Expressions

Grep

grep "keyword" file.txt
grep "^keyword" file.txt # ^ will find your keyword that starts with the line
grep -i "keyword" file.txt # Makes it case insenstive
grep -n "keyword" file.txt # returns back which line your keyword was found.
grep -C 1 "keyword" file.txt # Gives the line before and the line after your keyword.
grep -v "someword" file.txt # Gives back patterns that dont match yours.
grep "Dev[To]*" file.txt # Finds all dev and devto and devt etc.
grep "^[1234567890]" file.txt # finds all lines starting with a number.
grep "[@qwertyuiopasdfghjklzxcvbnm].com" file.txt # finds all emails. 

Enter fullscreen mode Exit fullscreen mode

SED

sed 's/Yo/Sup/' file.txt # Replaces first occurrence of Yo with Sup.
sed 's/Yo/Sup/g' file.txt # Replaces all matching on each line.
sed -i's/Yo/Sup/g' file.txt # This will modify the file. The other ways only modify what is show in the terminal.
sed '3d' file.txt # Deletes the 3rd line in the file
sed '1i\First line' file.txt # Adds the text "First line" to the file.txt
sed '$a\Last line' file.txt # Adds the text "Last line" to end of the file.
sed -e 's/Yo/Sup/g' -e 's/joshua/Joshua/g' file.txt # -e allows for mutiple commands.
sed 's/[Ww]orld/Galaxy/g' file.txt # RegEx finds any World or world and replaces with Galaxy.
Enter fullscreen mode Exit fullscreen mode

AWK

awk '{print $1}' file.txt # Prints the first word of each column
awk '{print $1, $2}' file.txt # Prints the first and second word of each line
awk '$2 > 28 {print $1 " is over 20"}' file.txt # Looks at second word of each line and compares it to see if its greater than 28 then print it.
awk 'NR > 1 {sum += $2} END {print "Average age:", sum/(NR-1)}' awk_test.txt # Checks if name records is greater than 1.
Enter fullscreen mode Exit fullscreen mode

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more