Home > Software engineering >  How to delete a line from a file that matches exactly to a string from a defined variable? bash
How to delete a line from a file that matches exactly to a string from a defined variable? bash

Time:10-30

I am writing a bash script to do various things in a generalized format. Initially, the script begins by declaring a variable set to the contents of a file, which we can call "file1.txt".

file1.txt will contain only 1 line which that 1 line will have only an integer. Predicting what the integer will be is impossible. Additionally, once the variable is set to that integer, rereading the file1.txt in hope to re-set the variable to the same integer is not reliable. Therefore, it is imperative that we must generalize the integer as a variable in the script.

Additionally, there is another file, which we will call "file2.txt" that has many lines with each line having a unique integer in it. It is guaranteed that 1 line and only 1 line of this file will have the same integer we have set our variable to.

Using only the variable that is set to this integer, what command can be used to remove the line from "file2.txt" that contains exactly the desired integer.

I have tried using commands sed and auk, but I am having troubles using the variable as a strings.

Example of a file1.txt:

123

Example of a file2.txt:

456
86454768
35434586745
1231
123
12323
123123

The goal is to remove the line that matches exactly to "123" in file2.txt, or in this case the 5th line from file2.txt.

My current code:

#This is the only time we can read this file to set the variable
Number="$(cat ./file1.txt)"

#Now we need to remove whatever number $Number is from file2.txt
(unknown command here)

I have already tried awk and sed, but to no avail. I am probably using syntax incorrectly. Here are examples of failed commands:

  • awk '$0 != $Number' < ./file2.txt
  • awk [ $0 != $Number ] < ./file2.txt
  • sed -i '/^$Number$/d' ./file2.txt
  • sed -i '/^"$Number"$/d' ./file2.txt
  • sed -i '/^(($Number))$/d' ./file2.txt

Any help would be greatly appreciated!

CodePudding user response:

$ awk 'NR==FNR{a[$0]; next} !($0 in a)' file1.txt file2.txt
456
86454768
35434586745
1231
12323
123123

or if you have the target value in a variable number:

grep -vFx "$number" file2.txt
  • Related