Wednesday, October 3, 2018

Sed Examples for Append, Insert and Replace a line in file

Sed For Append, Insert and Replace a line in a file
Append a Line :-
Syntax :-
sed 'ADDRESS a\
    Line which you want to append' filename

    (OR)

sed '/PATTERN/ a\
    Line which you want to append' filename


Example1 :-Append a line after the 2nd line of the file

sed '2 a\
Add H/W - Mouse, Headphone' config_details.txt


Example2 :-Append a line after the matching word in a line of the file


sed '/Window/ a\
Add H/W - Mouse, Headphone' config_details.txt


Example3 :- Append a line at the end of the file

sed '$ a\
Add H/W - Mouse, Headphone' config_details.txt

Insert a Line :-

Syntax :-
sed 'ADDRESS i\
    Line which you want to append' filename

    (OR)

sed '/PATTERN/ i\
    Line which you want to append' filename


Example1 :-Append a line before the 2nd line of the file

sed '2 i\
Add H/W - Mouse, Headphone' config_details.txt


Example2 :-Append a line before the matching word in a line of the file


sed '/Window/ i\
Add H/W - Mouse, Headphone' config_details.txt


Example3 :- Append a line before last line of the file

sed '$ i\
Add H/W - Mouse, Headphone' config_details.txt


Replace a Line :-

Syntax :-

sed 'ADDRESS c\
    Line which you want to append' filename

    (OR)

sed '/PATTERN/ c\
    Line which you want to append' filename


Example1 :-Replace 2nd line of the file

sed '2 c\
Add H/W - Mouse, Headphone' config_details.txt


Example2 :-Replace matching word line of the file


sed '/Window/ c\
Add H/W - Mouse, Headphone' config_details.txt


Example3 :- Replace last line of the file

sed '$ c\
Add H/W - Mouse, Headphone' config_details.txt

No comments:

Post a Comment

Remove CTRL-M characters from a file in UNIX

 We can remove ^M by below methods 1st Method - Using sed command Type below command:    sed -e "s/^M//" filename > newfilena...