Sometimes, you need to replace content of the first line of a file in your Linux system. This might be to update a configuration, correct a mistake, or add some new information. You can use the following basic syntax to do so:
sed '1 s/^.*$/New Content/' sample.txt
This command will replace first line content with New Content
in given file.
Practical Guide to Replace First Line
The sed
command is a powerful tool for editing files in Linux. You can use it to replace text, delete lines, and perform many other tasks. Here, we will use it to replace the first line of a file.
- Create a Sample File: First, let’s create a sample file to work with. Use the following command to create a file named
sample.txt
with some text.echo -e "First Line\nSecond Line\nThird Line" > sample.txt
This command will create a file named
sample.txt
with three lines of text. - View the File: You can view the contents of the file using the
cat
command.cat sample.txt
You should see the following output:
First Line Second Line Third Line
- Replace the First Line: Now, let’s replace the first line with new text. Use the following
sed
command:sed '1 s/^.*$/New First Line/' sample.txt
This command breaks down as follows:
sed
: A stream editor used for parsing and transforming text in files or streams.1
: Specifies that the operation should only apply to the first line of the file.s/^.*$/New First Line/
: The substitution command:^
: Matches the beginning of the line..*
: Matches everything on the line.$
: Matches the end of the line.New First Line
: The replacement text.
sample.txt
: The name of the file to process.
- View the Updated File: Check the file again to see the changes.
cat sample.txt
You should see the following output:
New First Line Second Line Third Line
Conclusion
Using the sed
command, you can easily replace the first line in a file on your Linux system. This is a simple yet powerful way to update files without manually editing them. By following these steps, you can quickly make changes to your files and streamline your workflow.