I have a database of readers and I would like to lend them a book and write it into the database.



753     Leonardo DaVinci    davinci@gmail.com   321654987   Lended Books:

grep "Leonardo" database_readers.txt | sed  "s/\(.*\):/\1: Narnie/"

With this command I only output the line with book Narnie added at end of the line, but how do I change the line in the file?

Thank for any advice

  • I don't mean add a line at the end of file, but change the line. Or if someone would give a solution to delete the line and add the new line with reader and new book added at the end of the line – Mafi May 25 '16 at 15:12
sed -i -e '/Leonardo/ s/$/ Narnie/' database_readers.txt

This uses sed's in-place edit option (-i) to search for all lines matching the regexp Leonardo, and replace the end-of-line anchor ($) with a single space and the word Narnie. This effectively appends the Narnie to the end of the matching lines.

Be careful with the regexp search pattern - it's easy to match more lines than you were expecting. Test first with:

sed -n -e '/Leonardo/ s/$/ Narnie/p' database_readers.txt

The -n option combined with the p at the end of the s/// makes sed print out ONLY the lines that were changed. Do NOT use this with sed -i unless you want to delete ALL unchanged lines from your file.

Anyway, if that prints out more lines than you were expecting then change Leonardo to Leonardo DaVinci or ^753[[:space:]]\+ (assuming that the number at the beginning of the line is a unique ID), and try again until it changes only the line(s) you were expecting it to.

For anything more complicated than that, you may want to look into using sqlite (or even mysql or postgresql) rather than a flat text file. Or use a language like perl which has many library modules for manipulating flat-file databases.

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.