Removing lines with strings from text files on Linux/Mac OS X

I used this technique to remove strings from bash history file containing passwords and other sensitive data on a Mac OS X shell (command line). In my case, this was a precautionary measure to make sure I erase any sensitive data from history files. For example, this is important for folks who enter mysql username and password on command line (with the 'mysql -p' command).

Lets say you want to remove lines containing the string 'password' (without quotes) from bash history file, then you'd use the awk command below. Please make a secure/encrypted backup copy of the original file in case you need it in future or have to restore for any reason:

awk '!/password/' ~/.bash_history > temp && mv temp ~/.bash_history

Please note that the command above erases lines and prints remaining content into a temporary file (named temp in example above). Then, moves (using mv in example above) the temporary file to original bash_history file.

Another technique is to use sed in a similar fashion.

sed '/password/d' ~/.bash_history > temp && mv temp ~/.bash_history

Bash history is stored in ~/.bash_hisotry file for the current user.

Did this tutorial help a little? How about buy me a cup of coffee?

Buy me a coffee at ko-fi.com

Please feel free to use the comments form below if you have any questions or need more explanation on anything. I do not guarantee a response.

IMPORTANT: You must thoroughy test any instructions on a production-like test environment first before trying anything on production systems. And, make sure it is tested for security, privacy, and safety. See our terms here.