Saturday, 23 January 2016

How To Replace Text In Specific Line Using Sed In Unix/Linux

In this article we will see how to replace a string/word in a specific line(s) using sed command. We will use F_Input_File.txt for explanation:

Input File: F_Input_File.txt
1001|A1|JPN|5000|Y
1002|A2|USA|6000|Y
1003|A3|UK|6000|Y
1004|A4|GER|7000|Y
1005|A5|CAN|8000|Y

Replacement In Nth Line

$ sed '5 s/Y/N/' F_Input_File.txt

Output: Will replace Y with N in 5th line only.
1001|A1|JPN|5000|Y
1002|A2|USA|6000|Y
1003|A3|UK|6000|Y
1004|A4|GER|7000|Y
1005|A5|CAN|8000|N

Replacement In Specific Lines ( Between Mth, Nth)

$ sed '3,5 s/Y/N/' F_Input_File.txt
[OR]
$ sed '3,5 s/Y/N/g' F_Input_File.txt
[OR]
$ sed '3,$ s/unix/linux/g' F_Input_File.txt


Output: All Will replace Y with N from line number 3 to 5 only. $ represent last line of the file.
1001|A1|JPN|5000|Y
1002|A2|USA|6000|Y
1003|A3|UK|6000|N
1004|A4|GER|7000|N
1005|A5|CAN|8000|N

Replacement Based On Pattern (or) Word/String Matching

$ sed '/USA/ s/Y/N/' F_Input_File.txt

Output: It will replace Y with N in the line(s) having USA.
1001|A1|JPN|5000|Y
1002|A2|USA|6000|N
1003|A3|UK|6000|Y
1004|A4|GER|7000|Y
1005|A5|CAN|8000|Y


Note: All the above listed solution will not change the data in file, sed will display the updated data at console only.If you want to update the data in file then redirect it in a temp file and use that file.

Keep Reading, Keep Learning, Keep Sharing...!!

2 comments:

  1. Nice, I like your effort, So here is a great converter which will work in a great way for you;

    File Converter Free

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...