5. Extended Examples
1. Example 01
Here are scripts in Bash, Perl, Ruby, and Python to find all .conf
files on your computer.
1.1 Bash Script
You can use the find
command in Bash to search for .conf
files.
#!/bin/bash# Find all .conf files on the systemfind / -type f -name "*.conf" 2>/dev/null
/
: Search starting from the root directory.-type f
: Look for files only (not directories).-name "*.conf"
: Match files with a.conf
extension.2>/dev/null
: Suppress permission denied errors.
1.2 Perl Script
In Perl, you can use the File::Find
module to recursively search for .conf
files.
#!/usr/bin/perluse strict;use warnings;use File::Find;
# Start search from the root directorymy $start_dir = '/';
# Subroutine to process each file foundsub find_conf_files { if (-f $_ && $_ =~ /\.conf$/) { print "$File::Find::name\n"; }}
# Use find to search for .conf filesfind(\&find_conf_files, $start_dir);
File::Find::find
: Recursively finds all files in the directory.-f $_
: Checks if the file exists.$_ =~ /\.conf$/
: Regex match for.conf
files.
1.3 Ruby Script
Ruby provides the Find
module to traverse directories.
#!/usr/bin/env rubyrequire 'find'
# Start searching from the root directorystart_dir = '/'
Find.find(start_dir) do |path| if File.file?(path) && path.end_with?('.conf') puts path endend
Find.find
: Recursively searches from the specified directory.File.file?
: Checks if the path is a file.end_with?('.conf')
: Matches.conf
file extensions.
1.4 Python Script
In Python, you can use the os
and fnmatch
modules to find .conf
files.
#!/usr/bin/env python3import osimport fnmatch
# Start searching from the root directorystart_dir = '/'
# Walk through all directories and filesfor dirpath, dirnames, filenames in os.walk(start_dir): for filename in fnmatch.filter(filenames, '*.conf'): print(os.path.join(dirpath, filename))
os.walk
: Recursively traverses directories.fnmatch.filter
: Matches files with the.conf
extension.
1.5 Running the Scripts
-
Save each script in a separate file (e.g.,
find_conf.sh
,find_conf.pl
,find_conf.rb
,find_conf.py
). -
Make each script executable (for Bash, Perl, and Ruby):
Terminal window chmod +x find_conf.shchmod +x find_conf.plchmod +x find_conf.rb -
Run the scripts:
- Bash:
./find_conf.sh
- Perl:
./find_conf.pl
- Ruby:
./find_conf.rb
- Python:
python3 find_conf.py
- Bash:
These scripts will recursively search your system for .conf
files starting from the root directory (/
). Depending on your system permissions, you may need to run them as root using sudo
.
Example 02
Here’s a Perl subroutine that takes a file name and a search term as parameters, opens the given file, and prints all lines where the search term appears:
#!/usr/bin/perluse strict;use warnings;
# Subroutine to search for a term in a filesub search_in_file { my ($filename, $search_term) = @_;
# Open the file for reading open my $fh, '<', $filename or die "Could not open file '$filename': $!";
# Loop through each line in the file while (my $line = <$fh>) { # Print the line if the search term is found if ($line =~ /\Q$search_term\E/) { print $line; } }
# Close the file handle close $fh;}
# Example usage of the subroutinemy $file = 'example.txt'; # Replace with your file pathmy $term = 'search term'; # Replace with your search termsearch_in_file($file, $term);
Explanation:
sub search_in_file { ... }
: Defines the subroutine.- Parameters:
$filename
: The name of the file to open.$search_term
: The term to search for in the file.
open my $fh, '<', $filename or die ...
: Opens the file in read mode (<
). If the file cannot be opened, the program will terminate with an error message.while (my $line = <$fh>) { ... }
: Reads the file line by line.\Q$search_term\E
: Ensures any special characters in the search term are treated literally in the regular expression.print $line
: Prints the line if the search term is found in it.close $fh
: Closes the file after reading.
Usage:
- Replace
example.txt
with the path to the file you want to search. - Replace
'search term'
with the search term you’re looking for.
This script will print all lines from the specified file where the search term appears.
3. Example 03
Here are examples of programs in Python and Ruby that parse a .csv
file, including functions to print the header and contents.
3.1 Python Program:
import csv
def print_header(filename): """Prints the header of the CSV file.""" with open(filename, mode='r', newline='') as file: reader = csv.reader(file) header = next(reader) # Get the first row as the header print("Header:", header)
def print_contents(filename): """Prints the contents of the CSV file.""" with open(filename, mode='r', newline='') as file: reader = csv.reader(file) next(reader) # Skip the header for row in reader: print(row)
# Example usagecsv_file = 'example.csv' # Replace with your CSV file pathprint_header(csv_file)print_contents(csv_file)
3.2 Ruby Program
require 'csv'
def print_header(filename) """Prints the header of the CSV file.""" CSV.foreach(filename).with_index do |row, index| if index == 0 puts "Header: #{row.join(', ')}" break end endend
def print_contents(filename) """Prints the contents of the CSV file.""" CSV.foreach(filename).with_index do |row, index| next if index == 0 # Skip the header puts row.join(', ') endend
# Example usagecsv_file = 'example.csv' # Replace with your CSV file pathprint_header(csv_file)print_contents(csv_file)
Explanation:
-
Python:
csv
Module: Used for reading and writing CSV files.print_header
Function:- Opens the CSV file and reads the first row to print the header.
print_contents
Function:- Reads the remaining rows and prints each row’s contents.
-
Ruby:
csv
Library: Standard library for handling CSV files.print_header
Function:- Uses
CSV.foreach
to iterate through the CSV file and prints the first row as the header.
- Uses
print_contents
Function:- Similar to
print_header
, but skips the first row and prints the remaining rows.
- Similar to
Usage:
- Replace
example.csv
with the path to your CSV file in both programs. - Run the respective program in your Python or Ruby environment.
Both programs will print the header and the contents of the specified CSV file.