I am trying to create a bash script that will manage a basic inventory system for a friend. Everything he wants to inventory has a barcode, that when scanned, returns a 6 digit number (EX. 000001). I have a piece of code that is supposed to take any input, call it $current, then find $current in data.txt and delete the line. When i am done entering codes, i enter 0 to stop

I couldnt get sed to replace the text in the file directly, so i had it copy to a different file, overwrite the original, then delete the copy. Whenever i run this piece of the file though, it freezes at the sed command and stops running, i can type whatever i want and it wont do anything, including the exit command "0".

read current
until [ $current -eq 0 ]
   sed '0,/$current/{/$current/d;}' >> data1.txt
   cp data1.txt data.txt
   rm data1.txt
   read current

You didn’t give sed any input, so it’s waiting for it on stdin. You probably want to edit data.txt in place:

sed -i "0,/$current/{/$current/d;}" data.txt

This saves you the cp and rm calls. Note that I used double quotes for the expression, variables are not expanded in single quotes.


Note that variable interpolation into a sed script is never a good idea. Should someone enter .*, your script would delete all lines. Should someone enter /, sed will output an error. It is a very fragile approach.

To delete the first line containing a certain string, I suggest using awk and its index function:

awk -i inplace 'index($0,c)&&!f{f=1;next}1' c="$current" file

Test run:

$ cat file
aaa / ccc
/ eee fff

$ current=/

$ awk 'index($0,c)&&!f{f=1;next}1' c="$current" file
/ eee fff

$ sed "0,/$current/{/$current/d;}" file
sed: -e expression #1, char 5: unknown command: `/'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.