r/badcode • • May 25 '20

[deleted by user]

[removed]

23 Upvotes

15 comments sorted by

View all comments

8

u/mathishard821 May 31 '20

Sounds a lot like string manipulation to me, so there's really only one tool for the job! Behold, a database written in sed!

#n
:readdb
/---/!{
	N; b readdb
}
s/\(^\n\|\n---$\)//; h
:top
n

/^get/{
	G
	s/^get \([[:alnum:]]*\)\n\(\1:\([[:alnum:]]*\)\n\|.\)*/\3/p
	$b end; b top
}
/^keys/{
	g; s/:[[:alnum:]]*//gp; $b end; b top
}
/^delete/{
	x; s/\(^\|\n\)/\1@/g; x; G
	:trydelete
	/^delete \([[:alnum:]]*\)\n[^@]*@\1/{
		s/\n\?@[[:alnum:]]*:[[:alnum:]]*//
		s/@//g
	}
	s/@\([[:alnum:]]*:[[:alnum:]]\)/\1/
	/@/b trydelete
	s/^[[:print:]]*\n//g
	h; s/.*/OK/p; $b end; b top
}
/^set/{
	x; s/\(^\|\n\)/\1@/g; x; G
	:tryset
	/^set \([[:alnum:]]*\) \([[:alnum:]]*\)\n[^@]*@\1/{
		s/\n\?@[[:alnum:]]*:[[:alnum:]]*//
		s/@//g
	}
	s/@\([[:alnum:]]*:[[:alnum:]]\)/\1/
	/@/b tryset
	s/^set \([[:alnum:]]*\) \([[:alnum:]]*\)/\1:\2/
	h; s/.*/OK/p; $b end; b top
}

:end
x; s/\n\?$/\n---/; w out.txt

A database is a text file in the following format:

key1:value1
key2:value2
key3:value3
---

To run this beautiful program, use sed -f script.sed db.txt commands.txt, or pipe your command(s) in through stdin. The resultant database is written to out.txt.

Pros:

  • Harness the full power of sed!
  • Built-in backups generated on each and every command, just throw away the output file if you run the wrong one!