sed is a powerful command-line tool in Unix/Linux that allows you to perform basic text transformations on an input stream (a file or input from a pipeline). It’s commonly used for:
Searching: Finding lines that match a pattern.
Editing: Modifying text by substituting, inserting, deleting, or appending text.
Displaying: Printing specific lines based on patterns.
The head command in Unix/Linux is used to display the beginning of a file or the first few lines of its content.
Case 1: To collect data from a file that contains continuous lines of text.
# Example:# Suppose we have data like this──(kali㉿kali)-[/tmp/temp_workspace]└─$catnote.txtDave's password list:Windowrickc137davesuperdavemegadaveumbrellaNote to myself:New password policy starting in January 2022. Passwords need 3 numbers, a capital letter and a special character
We want to fetch the data from note.txt. We want all the value from Window to umbrella .
The command sed 's/\bbuf\b/shell/g' replaces every whole word buf with shell in the input text, ensuring it doesn't affect words like buffer.
Case 2: If we want to delete last few lines from file.
Suppose we want to delete last four lines from /etc/john/john.conf file. So, We can use head command with -n and -4 (It is minues 4).
Case 3: Deleting particular line number and displaying its content.
We will use sed command for this.
1d: Tells sed to delete the first line.
-i: Edits the file in place.
This deletes the last line from Hosts the file. Run Multiple times to delete multiple last lines.
Deprecated function
Case 4: Special case of changing the value of x in ~/.zshrc file
I store the value in ~/.zshrc file to ease the process of fatching ip.
# Testing command:
sed -n '/Window/,/umbrella/p' note.txt
# sed -n '/start_pattern/,/end_pattern/p': Ideal for ranges if lines are grouped together.
# If got the result we want then we will save the result in new file.
sed -n '/Window/,/umbrella/p' note.txt > username.list
sed -i "s/192\.168\.45\.[0-9]\+/$IP_KALI/" shell.php
sed 's/\bbuf\b/shell/g'
head -n -4 /etc/john/john.conf
# This command will display all the content of mentioned file expect last four lines.
# Way to save result:
head -n -4 /etc/john/john.conf > temp && sudo mv temp /etc/john/john.conf