Some time we face situation where we need to either insert some records or line separator in file or need to change the complete line which matches the criteria.
Let See how to implement the same using sed command.
Let See how to implement the same using sed command.
Input_File: F_Input_File
1001|A00121|NOKIA-1100|Y
SYNTAX:
sed '<N/Pattern> [a/i/c] <Line To Be Appended /Inserted /Replaced>' F_Input_File.txt
N -> Line Number After Which File will be appended.
a -> Append After the Matching line or line number
i -> Insert Before the Matching line or line number
c -> change the matching line or line number
Pattern-> Pattern Matching/Regular Expression
Append: Add A line After The Match
$ sed '1 a "*************************"' F_Input_File.txt
[OR]
$ sed '/A00121/ a "*************************"' F_Input_File.txt
Output:
1001|A00121|NOKIA-1100|Y
*************************
Insert: Add A line Before The Match
$ sed '1 i "-------------------------"' F_Input_File.txt
[OR]
$ sed '/A00121/ i "-------------------------"' F_Input_File.txt
Output:
-------------------------
1001|A00121|NOKIA-1100|Y
Change: Change Matching Line(s)
$ sed '1 c "****PRODUCT OUT OF STOCK**"' F_Input_File.txt
[OR]
$ sed '/A00121/ c "****PRODUCT OUT OF STOCK**"' F_Input_File.txt
Output:
****PRODUCT OUT OF STOCK**"
The above all method will display the updated/changed data on terminal but the changes will not be permanent in the original file.To make changes permanent, we need to use -i switch, as shown below:
$ sed -i '/A00121/ a "*************************"' F_Input_File.txt
$ sed -i '/A00121/ i "-------------------------"' F_Input_File.txt
$ sed -i '/A00121/ c "***PRODUCT OUT OF STOCK**"' F_Input_File.txt
And again, if your version of sed is not supporting -i switch then we can always go the basics to achieve the same using redirection operator. Already explained in following post
Keep Reading, Keep Learning, Keep Sharing..!!!
No comments:
Post a Comment