0

I'm trying to change the filename from prod.test.PVSREGPLUS20170915-6777.DAT.gpg to PVSREGPLUS20170915-0003.DAT.gpg

I used this

DTE=$(date +%I);ls  prod.test* |cut -f 3,4,5 -d .|sed "s/\-/-00$DTE/" |cut -c 1-23,28-35

My problem is I need this command in a shell script

"#! /bin/bash

DTE=$(date +%I)

newfile=$(ls  prod.test* |cut -f 3,4,5 -d .|sed "s/-*./$DTE/"|cut -c 1-23,28-35

The sed can't do expansion, would awk be able to do this? Any help would be greatly appreciated. Thanks

Rahul Verma
  • 2,946
  • 14
  • 27
Mark Scheck
  • 111
  • 4
  • What do you mean `The sed can't do expansion`? sed can do the expansion just fine. Your shell script has other issues of course (e.g. extra `"` at the start and missing `)` at the end). Run it through `shellcheck`. – Ed Morton Sep 26 '17 at 20:09
  • You changed the `sed` command: the version in your script will change the **first character** to the DTE value. – glenn jackman Sep 26 '17 at 20:16
  • 1
    Tangential to the question, I'd suggest looking into `perl-rename` (see e.g. [this](https://stackoverflow.com/questions/22577767/get-the-perl-rename-utility-instead-of-the-built-in-rename)). – David Z Sep 26 '17 at 20:20

1 Answers1

0

The simplest way to do this is with a for-loop over a glob pattern, then use paramater expansion to remove the prefix

prefix="prod.test."
hour=$(date '+%I')
for f in "$prefix"*; do 
    new=$( echo "${f#$prefix}" | sed 's/-[[:digit:]]\+/-00'"$hour"'/' )
    echo mv "$f" "$new"
done

We really don't need sed: extended patterns and more parameter expansion

shopt -s extglob
for f in "$prefix"*; do 
    new=${f#$prefix}
    new=${new/-+([0-9])/-00$hour}
    echo mv "$f" "$new"
done

Remove "echo" if it looks good.

Or, with the perl rename as suggested in the comments:

rename -v -n 's/prod\.test\.//; use Time::Piece; s{-\d+}{"-00" . (localtime)->strftime("%I") }e' prod.test.*

Remove "-n" if it looks good.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • Thanks I really appreciate it, time to hit the books harder. What do you guys recommend. Glenn, you're a master! – Mark Scheck Sep 27 '17 at 18:47