0

I am new bee for shell script. Please redirect me to correct post if this question is redundant.

I have file.txt which has text like below and want to change the 2nd row in file

Property1=0
Property2=0 50 14 1/1 * ? *
Property3=0

I want to replace 2nd line to change 50 14 to current time, file will look like

Property1=0
Property2=0 58 15 1/1 * ? *
Property3=0

and next time it will look like

Property1=0
Property2=0 03 16 1/1 * ? *
Property3=0

Please help me how to change 2nd line.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Shikha A
  • 178
  • 3
  • 16

2 Answers2

3

You can use sed to change the second line

sed '2s/.*/Property2=0 58 15 1\/1 * ? */' test

It seems like you're trying to increment, but I don't see the pattern in the third example

Barmar
  • 741,623
  • 53
  • 500
  • 612
willpnw
  • 755
  • 1
  • 6
  • 23
2

This is probably easier done using awk than sed.

awk -v min=$(date +%M) -v hour=$(date +%H) 'NR == 2 { $2 = min; $3 = hour } 1' file > file.new

The two date commands set awk variables to the current time. NR == 2 matches line 2 in the file, then it replaces the 2nd and 3rd fields with those time variables. 1 at the end causes the current line to be printed.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • SO you want me to create a new file "file.new" everytime I want to change this time? If this is the case, then I should go for sed – Shikha A Aug 12 '16 at 00:07
  • Recent versions of GNU awk have an `inplace` option to replace the input file. See http://stackoverflow.com/questions/16529716/awk-save-modifications-inplace – Barmar Aug 12 '16 at 00:08
  • 1
    @ShikhaA even if your awk doesn't have inplace editing, typing `awk 'script' file > tmp && mv tmp file` really isn't that much more effort than typing `sed -i tmp 'script' file` especially when the sed script will be less concise than the awk script. – Ed Morton Aug 12 '16 at 00:15