Preview changes made with sed

Preview changes made with sed

When making changes to a file with sed, you might want to see what would be changed before you make the change.

Let's say you are trying to change all instances of to in file.conf but you are not completely confident you want all occurences changed. The following command will make the changes by directly editing file.conf

Edit file in place
sed -i 's/' file.conf
This command will search for and replace with and edit the file file.conf directly.

The problem with that command is that the changes will get committed even though you are unsure that you wanted all occurrences changed. Changing back using another sed command might be a problem if there were already some entries which you don't want to change to To allow undoing a change made with sed -i, sed provides the ability to make a back (you could manually create a back before hand, but sed makes it a little easier).

Edit file in place with backup
sed -i.bak 's/' file.conf
-i.bak will create a backup file of the original with .bak as an extension

You could now diff file.conf and file.conf.bak to see the changes and if you are unhappy, you can restore from file.conf.bak. This doesn't completely solve the problem though. If file.conf was a live config file, you might still create a problem if you didn't need to change every occurrence.

Another option would be to have sed preview the changes without writing to disk.

Preview file with changes
sed 's/' file.conf
This command will output the entire file with you changes made

You can now review what the file would look like with the changes. The problem now is that the file might be quite large and reviewing it is time consuming and you might miss something.

You can have sed only display the lines that would change using

Preview only lines that would change
sed -n 's/' file.conf
The -n tell sed to not automatically print all lines. The the p at the end tell sed to print the lines that match your search (

You will now see all the lines that would change and what they would look like with the changes applies. This method is pretty good, but there is one other option that I like even more.

Compare the lines that would change with the original
sed 's/' file.conf | diff file.conf -

This will output the entire file like the command mentioned above, however, the output will be piped into diff. Diff will now compare this output on the right (the - in diff tells it to compare stdin) to file.conf on the left. You will now see only the changed lines and you will see both the original and the changed versions. If your search and replace pattern worked, you can now run the first command (the sed -i) to have sed make the changes to file.conf