SED replacing the word after a word in a file

>> Tuesday 13 November 2018



There is an application that writes a particular command into a log file whenever it runs.  And that command includes a password switch.  Which means the password is joyfully sat in a log file.  Even though you have to be able to log onto the server, and have permissions to read the log, it is still not ideal.  To strip the password out of the log I run:

sed -i 's/--password[^ ]* /--password replaced /g' myfile.txt

it says find the string "--password morecharacters " and change it to "--password replaced "

Lets break it down:

-i - edit file in place

's/regexp/replacement/g'
Attempt to match regexp against the pattern space. If successful, replace that portion matched with replacement.

[^ ]* regular expression for match every character except a space - note there is a space after the ^  and before the ] and after the *
so it is saying match the word --password and whatever comes after it ignoring the first space
and up to the next space.       
      
g  do it for all iterations found in the file (global replace) 



cat myfile.txt:
          here be my command --password mypassword --anotherswitch and more words

sed -i 's/--password[^ ]* /--password replaced /g' myfile.txt

cat myfile.txt:

          here be my command --password replaced --anotherswitch and more words



  





0 comments:


  © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

Back to TOP