Question
Answer and Explanation
To replace the last line of a text file using a Bash script, you can use several approaches. Here's a common and effective method using sed
and head
:
Method: Using sed
and head
This method involves first extracting all lines except the last one using head
, and then appending the new line using sed
.
Steps:
1. Extract All Lines Except the Last One:
Use the head
command with the -n
option to print all lines except the last one. To determine how many lines to print, you need to count the total lines in the file and subtract 1.
2. Append the New Line:
Use sed
to append the new line to the file.
Example Bash Script:
Assume your file is named file.txt
and you want to replace the last line with "This is the new last line."
#!/bin/bash
file="file.txt"
new_last_line="This is the new last line."
# Count the number of lines in the file
line_count=$(wc -l < "$file" | awk '{print $1}')
# If the file is not empty:
if [ "$line_count" -gt 0 ]; then
# Extract all lines except the last one
head -n $((line_count - 1)) "$file" > temp.txt
# Append the new last line
echo "$new_last_line" >> temp.txt
# Replace the original file with the modified content
mv temp.txt "$file"
else
# File is empty, just add the new line
echo "$new_last_line" > "$file"
fi
echo "Last line replaced successfully."
Explanation:
1. `file="file.txt"`: This sets the variable file
to the name of your text file.
2. `new_last_line="This is the new last line."`: This sets the variable new_last_line
to the new line you want to insert.
3. `line_count=$(wc -l < "$file" | awk '{print $1}')`: This counts the number of lines in the file using wc -l
and extracts the number using awk
.
4. `if [ "$line_count" -gt 0 ]; then`: Check if the file is not empty before proceeding.
5. `head -n $((line_count - 1)) "$file" > temp.txt`: This extracts all lines except the last one and redirects the output to a temporary file named temp.txt
.
6. `echo "$new_last_line" >> temp.txt`: This appends the new line to the temp.txt
file.
7. `mv temp.txt "$file"`: This replaces the original file with the content of the temporary file.
8. `else echo "$new_last_line" > "$file"`: If the file is empty, this command simply puts the new line into the file.
How to Use:
1. Save the script to a file, for example, replace_last_line.sh
.
2. Make the script executable with chmod +x replace_last_line.sh
.
3. Run the script with ./replace_last_line.sh
.
This script effectively replaces the last line of your text file with the new line specified in the new_last_line
variable.