0
0
Bash Scriptingscripting~15 mins

awk field extraction in scripts in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Extracting Fields with awk in Bash Scripts
📖 Scenario: You have a text file with information about employees. Each line contains the employee's ID, name, and department separated by spaces.You want to write a bash script that extracts specific fields from each line using awk.
🎯 Goal: Build a bash script that reads the employee data and extracts the employee names using awk.
📋 What You'll Learn
Create a text file variable with employee data
Create a variable for the field number to extract
Use awk to extract the specified field from each line
Print the extracted fields
💡 Why This Matters
🌍 Real World
Extracting specific columns from text data is common when processing logs, reports, or CSV files in automation scripts.
💼 Career
Knowing how to use awk in bash scripts helps automate data extraction tasks in system administration, data analysis, and DevOps roles.
Progress0 / 4 steps
1
Create the employee data variable
Create a variable called employee_data that contains these exact three lines of text, each line separated by a newline character:
101 Alice Sales
102 Bob Marketing
103 Charlie IT
Bash Scripting
Need a hint?

Use double quotes and \n to separate lines inside the string.

2
Set the field number to extract
Create a variable called field_number and set it to 2 to represent the employee name field.
Bash Scripting
Need a hint?

Just assign the number 2 to the variable field_number.

3
Extract the specified field using awk
Use echo to send employee_data to awk. Use awk with the field variable field_number to extract that field from each line. Store the result in a variable called extracted_names.
Bash Scripting
Need a hint?

Use awk -v field="$field_number" '{print $field}' to print the chosen field.

4
Print the extracted names
Print the variable extracted_names to display the extracted employee names.
Bash Scripting
Need a hint?

Use printf "%s\n" "$extracted_names" to print each name on its own line.