6

Using /bin/bash on RHEL 5.8 and I want to automate editing a file. I need the script to search the file and replace a line in the file. Line example:

Other line
Current date 01121990
Other line

Search for this line and replace the date string with a predetermined date. I can't echo to a new file and enter in my date since this file will be copied from a server-specific file. Thanks!

  • 2
    sed would be the tool of choice here... – jasonwryan Mar 19 '16 at 23:16
14
your_date='your desired date'
sed -i "s/^Current date.*/Current date ${your_date}/" /path/to/file

That's the easiest way. This assumes that all lines that contains a date to replace also are the only lines to start with 'Current date'.

Note that the user level that runs this command must also have permission to edit that file.

-i means inline edit, which means you are editing the file directly.

^Current date.*

Means all lines starting with: Current date and ending in anything. In other words, replace the entire line with what is in the second /.../ part of the sed thing.

Double " are used around the sed statement so that variables will be used as variables, not strings.

  • Thanks Lizardx that's exactly what I need, tested it and it works great – Paul Mar 20 '16 at 0:52
  • great glad to hear it. – Lizardx Mar 20 '16 at 2:39
1

ed can do in-place editing of files as well! The inode number of the edited file remains unchanged.

file='/path/to/file'
your_date='your desired date'
ls -i "$file"
printf '%s\n' H ",g/^Current date.*/s//${your_date}/" wq | ed -s "$file"
ls -i "$file"

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.