Search code examples
bashquoting

Bash: Delete a line from a file matching a variable


I have four files named source, correct, wrong and not_found. I am trying to write a script in bash wherein I read each line from file named source, store the line as variable x, and match it against a condition.

If it passes, then I need to write that line to file named correct, but the catch is before writing into correct I need to check if the variable x is currently present in file named wrong and if yes delete it and then add the line to file named correct.

I have tried below, but it doesn't modify the file and neither gives me any output:

sed -i '/$x/d' ./wrong

Solution

  • As you have already understood, variables inside '...' are not expanded.

    If you replace the single-quotes with double-quotes, this will delete the matching line from ./wrong:

    sed -i "/$x/d" ./wrong
    

    But you also want to add the line to ./correct, if there was a match. To do that, you can run grep before the sed:

    grep "$x" ./wrong >> ./correct
    

    This will have the desired effect, but sed will overwrite ./wrong, even when it doesn't need to. You can prevent that like this:

    if grep "$x" ./wrong >> ./correct; then
        sed -i "/$x/d" ./wrong
    fi