- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to insert a text at the beginning of a file in Linux?
In order to insert text at the beginning of a text file we must be familiar with either the sed command as the sed commands can be used to solve the above problem.
Let’s first explore the sed command, which is short for stream editor. This command is used to perform different functions like find, replace, insert and many more on a particular file.
Consider we have a directory d1 in which two .txt files are present and the directory looks something like this −
immukul@192 d1 % ls -ltr total 8280 -rwxrwxrwx 1 immukul staff 4234901 Jul 7 17:41 file.txt -rw-r--r-- 1 immukul staff 105 Jul 16 09:30 somefile.txt
Now we want to change the contents of the file named somefile.txt and insert some text of our choice at the first line of the .txt file.
The contents of the somefile.txt before inserting anything in the file looks something like this
immukul@192 d1 % cat somefile.txt this file contains a new text stream and i am going to edit that stream yes i can do that ask jeffrey
Now in order to add some text to the first line we will make use of the command shown below
For Mac OS
sed -i "" '1s/^/Is this text added\n/' somefile.txt
sed -i '1s/^/Is this text added\n/' somefile.txt
immukul@192 d1 % cat somefile.txt Is this text added this file contains a new text stream and i am going to edit that stream yes i can do that ask jeffrey
- How to insert text at the beginning of the text box in Tkinter?
- How to format contents of a text file in the Linux system?
- Insert the string at the beginning of all items in a list in Python
- Python program to insert a new node at the beginning of the Doubly Linked list
- Python program to insert a new node at the beginning of the Circular Linked List
- Write a program in C++ to insert a Node at the beginning of the given Singly linked list
- How to insert a string in beginning of another string in java?
- How to create a text file and insert data to that file on Android using Kotlin?
- C# Program to remove a node at the beginning of a Linked List
- How to shrink or extend the size of a file in Linux?
- How to create text file and insert data to that file on Android?
- How to append text to a text file in C++?
- How to sort a file in-place in Linux?
- How to output colored text to a Linux terminal?
- How to read a text file in Python?