Friday, January 2, 2009

Insert, append, change lines using sed


Input file:
$ cat order789.txt
title:
PO for vessel unit1 const.
items:
fan:F34539
tube:L1245
driller:M4545
Description:
PO signed and verified by factory manager S K Lp
Date: Fri Jan 2 17:26:44 UTC 2009
Author: M Kumar

# Add the line "heater:M21789" after the line "items"
$ sed '
/items/ a\
heater:M21789
' order789.txt

Output:
title:
PO for vessel unit1 const.
items:
heater:M21789
fan:F34539
tube:L1245
driller:M4545
Description:
PO signed and verified by factory manager S K Lp
Date: Fri Jan 2 17:26:44 UTC 2009
Author: M Kumar

# Add the line "heater:M21789" after line number 3 (output would be same as above)
$ sed '
3 a\
heater:M21789
' order789.txt

# Insert a line "heater:M21789" before the line beginning with "fan"
$ sed '
/^fan/ i\
heater:M21789
' order789.txt

Output:
title:
PO for vessel unit1 const.
items:
heater:M21789
fan:F34539
tube:L1245
driller:M4545
Description:
PO signed and verified by factory manager S K Lp
Date: Fri Jan 2 17:26:44 UTC 2009
Author: M Kumar

# We can insert or add more than one line also.
$ sed '
4 i\
heater:M21789\
newitem:YYYYY
' order789.txt

Output:
title:
PO for vessel unit1 const.
items:
heater:M21789
newitem:YYYYY
fan:F34539
tube:L1245
driller:M4545
Description:
PO signed and verified by factory manager S K Lp
Date: Fri Jan 2 17:26:44 UTC 2009
Author: M Kumar


# One can change a line as well, e.g. to change the line beginning with "fan" with the line "BigFAN:F5757"
$ sed '
/^fan/ c\
BigFAN:F5757
' order789.txt

Output:
title:
PO for vessel unit1 const.
items:
BigFAN:F5757
tube:L1245
driller:M4545
Description:
PO signed and verified by factory manager S K Lp
Date: Fri Jan 2 17:26:44 UTC 2009
Author: M Kumar

In all the above cases one can mention the line numbers instead of the pattern before or after which one or multiple line(s) needs to be added/inserted or changed.

2 comments:

H@$! said...

Great post. Love it.

I have one problem.

----------------
# cart code list: 123455555
map $cart_country_code
$allow_list {
default yes;
}

mango {
# country export
default yes;
----------------

I want to add "Germany" under the function map "$cart_country_code
$allow_list" below default yes;

how can I do that.

Please assist

H@$! said...

Great post. Love it.

I have one problem.

----------------
# cart code list: 123455555
map $cart_country_code
$allow_list {
default yes;
}

mango {
# country export
default yes;
----------------

I want to add "Germany" under the function map "$cart_country_code
$allow_list" below default yes;

how can I do that.

Please assist

© Jadu Saikia www.UNIXCL.com