Last active
May 7, 2025 09:56
-
-
Save manojmohangit/8f38e0be3f94ed7096867341cb45780e to your computer and use it in GitHub Desktop.
Bash Script for toggling prefix in the last "n" lines of a file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# This script can be used to switch off some features from the configuration file. | |
# Usage: | |
# ./toggle_prefix.sh filename prefix num_lines | |
# Example: | |
# ./toggle_prefix.sh yourfile.txt ";" 4 | |
# Default values | |
default_file="custom-configuration.ini" | |
default_prefix=";" | |
default_num_lines=4 | |
# Assign positional parameters or use defaults | |
input_file="${1:-$default_file}" | |
toggle_prefix="${2:-$default_prefix}" | |
num_lines="${3:-$default_num_lines}" | |
# Temp file | |
temp_file=$(mktemp) | |
# Validate input file | |
if [[ ! -f "$input_file" ]]; then | |
echo "Error: File '$input_file' not found." | |
exit 1 | |
fi | |
# Count total lines in file | |
total_lines=$(wc -l < "$input_file") | |
start_line=$((total_lines - num_lines + 1)) | |
# Toggle prefix on the last N lines | |
awk -v start="$start_line" -v prefix="$toggle_prefix" '{ | |
if (NR >= start) { | |
if (index($0, prefix) == 1) { | |
sub("^" prefix, "", $0) | |
} else { | |
$0 = prefix $0 | |
} | |
} | |
}' "$input_file" > "$temp_file" | |
# Replace the original file | |
mv "$temp_file" "$input_file" | |
echo "✅ Updated '$input_file': Toggled prefix '$toggle_prefix' on last $num_lines lines." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment