Here’s a bash script that removes duplicate lines from a file selected by the user:
bash
#!/bin/bash
# Prompt the user to enter the file name
read -p "Enter the file name: " filename
# Check if the file exists
if [[ ! -f "$filename" ]]; then
echo "Error: File '$filename' does not exist."
exit 1
fi
# Remove duplicate lines and overwrite the original file
awk '!seen[$0]++' "$filename" > temp && mv temp "$filename"
echo "Duplicate lines removed from '$filename'."
Explanation:
Prompt for the file name:
The read command asks the user to input the file name.
Check if the file exists:
The [[ ! -f "$filename" ]] condition checks if the file exists and is a regular file.
If the file doesn't exist, the script prints an error message and exits with a non-zero status (exit 1).
Remove duplicate lines:
awk '!seen[$0]++' processes each line of the file:
$0 represents the current line.
seen is an associative array that tracks whether a line has been seen before.
!seen[$0]++ ensures only the first occurrence of each line is printed (subsequent duplicates are skipped).
The output is redirected to a temporary file (temp).
Overwrite the original file:
The mv temp "$filename" command replaces the original file with the deduplicated version.
Confirmation:
A message is displayed to inform the user that duplicate lines have been removed.
Example Usage:
Suppose you have a file called example.txt with the following content:
code
apple
banana
apple
orange
banana
grape
Run the script:
bash
$ ./remove_duplicates.sh
Enter the file name: example.txt
Duplicate lines removed from 'example.txt'.
After running the script, example.txt will look like this:
code
apple
banana
orange
grape
Alternative Methods:
If you prefer other tools, here are a few alternatives: