Saturday, 23 January 2016

How To Update A File Keeping Original File Using Sed In Unix/Linux

In this article we will see how to update file using sed instead of using temporary table or displaying data at terminal. We will see how can we keep the backup of original file, that can be used in case of any failure or data retrieval. We will use input file F_Input_File.txt for the same. Let see how to achieve it...!!

$ cat F_Input_File.txt
1001|A1|HR|5000|Y
1002|A2|FIN|6000|Y
1003|A3|HR|6000|Y
1004|A4|HR|7000|Y

$ sed -i .bak 's/FIN/HR' F_Input_File.txt
[OR]
$ sed -i.bak 's/FIN/HR' F_Input_File.txt


Output: It Will produce two files in the same directory, one with updated data (in Green) and one with original data (.bak file,  in blue)

$ ls
F_Input_File.txt
F_Input_File.txt.bak

$ cat F_Input_File.txt
1001|A1|HR|5000|Y
1002|A2|HR|6000|Y
1003|A3|HR|6000|Y
1004|A4|HR|7000|Y 

$ cat F_Input_File.txt.bak
1001|A1|HR|5000|Y
1002|A2|FIN|6000|Y
1003|A3|HR|6000|Y
1004|A4|HR|7000|Y

Note: In some of the Linux/Unix system first command may not work, in that case please use 2nd command. (there should not be any space between -i switch and extension)

Most Imp: If NO extension is given, no backup will be saved.

$ sed -i 's/FIN/HR' F_Input_File.txt

Output: Will update the file F_Input_File.txt and there will be no file available with original data (backup file)

If -i switch is not working in your version of Unix/linux, we can always go to the basics and achieve the same by using redirection.

$ sed 's/FIN/HR' F_Input_File.txt > F_Input_File.txt_tmp


Updated data is now available in F_Input_File.txt_tmp, we can rename the original file (F_Input_File.txt) to backup (F_Input_File.txt.bkp) and then rename the temporary file (updated file:F_Input_File.txt_tmp,) to original file(F_Input_File.txt).

$ mv F_Input_File.txt F_Input_File.txt.bkp
$ mv F_Input_File.txt_tmp F_Input_File.txt


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

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...