Search code examples
shellunixsolaris-10

How to compare a lines of a text file with a line of different text file and append the first one if they are not same


I want to compare particular line of two text file and update one of the file if they are not same.


Solution

  • Updating a line in a text file is technically not possible (unless the replacing line is of exactly the same length). You have to create a new file, which you can, in the end, move to the old one.

    From your tags, I assume that you are looking for a shell solution, which is maybe not a good idea. It's probably more convenient to do it in, for instance, Perl or Ruby or Python.

    One possibility is to use the commands head and tail, which allow you to dissect a file into parts. You can split your file into three parts: The part before the line in question, the line itself, and the lines which come after.

    Another possibility is to use a loop and the read command of the shell to process a file line by line, like this:

    while read line           
    do           
      ... # Decide here, whether to write $line or the replacement line          
    done <your_file