0

I have a Config.cfg file and I want to rename it by putting the value of 2nd line in the name of the file.

Example:

$ more Config.cfg 
!
!  Configuration last changed by user '%LICM%' at Tue Jul  4 15:17:04 2017
!
!
!
global synchronization option 2

Expected Result :

Config Jul  4 15:17:04 2017.cfg
  • Is the format of the second line always exactly the same? – a CVn Aug 1 '17 at 9:54
0

One way:

  • with sed, extract the 2nd line
  • with awk, extract the trailing fields and print the surrounding static text
  • if successful, rename the file with that generated value

Code:

val=$(sed -n 2p Config.cfg | 
      awk '{print "Config " $(NF-3) " " $(NF-2) " " $(NF-1) " " $NF ".cfg"}')
[[ -n "$val" ]] && mv Config.cfg "$val"
  • 2
    Why not use NR==2 in awk and skip the sed? – Eric Renouf Aug 1 '17 at 11:19
  • Certainly could! I wasn't sure I was going to use awk, so I started with sed to get line #2 and went from there. – Jeff Schaller Aug 1 '17 at 11:20
  • 2
    Fair enough! of course, this doesn't exactly produce the filename in the expected output either since a single digit day number will end up with 2 spaces between it and the month there and only 1 with yours – Eric Renouf Aug 1 '17 at 11:21
  • 1
    printf "Config %s %-2i %02i:%02i:%02i %04i.cfg", $(NF-3), $(NF-2), $(NF-1), $NF;. better yet, do it in perl which has a built-in rename() function. – cas Aug 1 '17 at 12:58
  • OTOH. deliberately making filenames with spaces - lots of spaces - in them on unix is just......wrong. use - or _ or .. and, more importantly, @Nydenn should use YYYY-MM-DD. It's the only date format that's competely unambiguous and sorts correctly. – cas Aug 1 '17 at 13:01
0

Only with sed you extract your filename:

mv file "$(sed -n '/Configuration/s/.*at [^ ]*/Config/p' 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.