How to change the attributes of a file in linux

>> Tuesday, 12 February 2019



I often want to change the timestamp of files when testing scripts so I can see whether the logic works with different ages of files etc.

use touch:


touch -a -m -t 201512180130.09 myfile


-a  change the access time
-m change the modification time
-t STAMP use [[CC]YY]MMDDhhmm[.ss] instead of current time


Read more...

Removing blank lines or replacing white spaces in a file

>> Monday, 24 December 2018

in vim:

:g/^$/d


:  put into a state for editing with regex commands

g for every line in the file

/  let's start

^  from the start of the line

$   to the end of the line (^$ together is a special instruction that says blank line)

/ next instruction

d delete it




with vi

 :g/^[ ]*$/d

there's a space in between those square brackets 

vim

:g/^\s$/d

\s means white spaces

remove blank lines from a file with sed:
sed -i '/^$/d' myfile.txt


Replace white spaces with commas:
:%s/\s\+/,/g

replace a word in vi

:g;myword;s;;replaceitwiththis;g

For replacing a word after a word see this post
Here is a useful link for regex expressions:


for vim:



Read more...

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



  





Read more...

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

Back to TOP