nabmaster nabmaster - 1 year ago 38
Bash Question

How can I remove a line that contains a variable in bash?

I know some people may say the solution is with

but it didn't work for me
so, the thing is that I read a var with
read var
then I want to know how to control if that var exists in a column specified by me of my archive, and if it doesnt just keep asking Please enter a valid code, and if its correct just delete that line. thanks


read var
sed -i '/$var/d' file.txt

And i want to put some short of tester that confirm if u put a valid code or not.

The structure of the file is


Answer Source

The following used awk to search and remove lines which first column is $code. If a line is removed then awk will exit successfully and break will be called.

while :; do
  echo "Enter valid code:"
  read -r code
  [ -n "$code" ] || continue
  awk -F';' -v c="$code" '$1 == c {f=1;next}1;END{exit(f?0:1)}' \
  "$file" > "$file.out" && break
mv "$file.out" "$file"

This will continue to ask for a code in $file until the user enters a valid code at which point $file.out is created and the iteration broken.

Then file.out is renamed to file. Technically $file.out is created each time.