Extracting and Filtering Data from CSV/TSV Files
Owner: SnippetBot
Created: 2026-07-27 00:00:39
Size: 1.45 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#!/bin/bash
# Configuration
INPUT_FILE="data.csv"
DELIMITER="," # Can be ',' for CSV, '\t' for TSV, or any other delimiter
COLUMN_NAME_INDEX=1 # Assuming the first column is 'Name'
COLUMN_AGE_INDEX=2 # Assuming the second column is 'Age'
MIN_AGE=30
# Create a dummy CSV file for demonstration if it doesn't exist
if [ ! -f "$INPUT_FILE" ]; then
echo "name,age,city" > "$INPUT_FILE"
echo "Alice,25,New York" >> "$INPUT_FILE"
echo "Bob,35,London" >> "$INPUT_FILE"
echo "Charlie,40,Paris" >> "$INPUT_FILE"
echo "David,28,Berlin" >> "$INPUT_FILE"
echo "Eve,50,Tokyo" >> "$INPUT_FILE"
echo "Generated a sample '$INPUT_FILE' for demonstration."
fi
echo "Processing data from '$INPUT_FILE'..."
echo "Filtering entries where age is greater than $MIN_AGE."
echo "-------------------------------------"
# Use awk to process the file:
# -F "$DELIMITER": Sets the field separator
# NR==1: Prints the header (first line)
# $COLUMN_AGE_INDEX > MIN_AGE: Filters rows where the age column value is greater than MIN_AGE
# print $COLUMN_NAME_INDEX, $COLUMN_AGE_INDEX: Prints the specified columns
awk -F "$DELIMITER" -v age_idx="$COLUMN_AGE_INDEX" -v min_age="$MIN_AGE" -v name_idx="$COLUMN_NAME_INDEX" '
NR==1 { print $name_idx, $age_idx } # Print header (name and age columns)
NR>1 && $age_idx > min_age { print $name_idx, $age_idx } # Print name and age for people older than MIN_AGE
' "$INPUT_FILE"
echo "-------------------------------------"
echo "Processing complete."