Practice your sed and awk skills with these challenging exercises
Try to solve each exercise on your own before looking at the solution. This will help reinforce your learning and improve your problem-solving skills.
Use sed to replace all occurrences of "apple" with "orange" in a file, but only on lines that contain the word "fruit".
Explanation: This sed command first matches lines containing "fruit", then performs the substitution on those lines only.
Use awk to calculate the average of numbers in the third column of a tab-separated file.
Explanation: This awk command sets the field separator to tab, sums up the third column, counts the lines, and calculates the average at the end.
Combine sed and awk to extract email addresses from a log file and count how many times each domain appears.
Explanation: This pipeline uses sed to extract email addresses, awk to isolate the domain part, then sorts and counts unique occurrences.
Use sed to replace all occurrences of "START" with "BEGIN" and "END" with "FINISH", but only within blocks of text between "SECTION" and "ENDSECTION".
Explanation: This sed command uses address ranges to limit the substitutions to the specified blocks of text.
Use awk to convert a CSV file with headers to JSON format.
Explanation: This awk script reads the headers, then formats each subsequent line as a JSON object.
Use sed to remove all XML tags from a file, leaving only the text content.
Explanation: This sed command removes anything between < and >, then deletes any resulting empty lines.
Use awk to analyze an Apache access log and report the top 5 IP addresses by number of requests.
Explanation: This pipeline extracts IP addresses, counts occurrences, sorts by frequency, and displays the top 5.
Create sample input files to test these solutions.
Modify the exercises to work with your own data or create variations to further challenge yourself.
For more advanced exercises and real-world scenarios, check out our additional resources: