简体   繁体   English

如何在变量中获取sed或awk命令

[英]How to get sed or awk commands in a variable

I'm trying to change the filename from prod.test.PVSREGPLUS20170915-6777.DAT.gpg to PVSREGPLUS20170915-0003.DAT.gpg 我正在尝试将文件名从prod.test.PVSREGPLUS20170915-6777.DAT.gpg更改为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 我的问题是我在shell脚本中需要此命令

"#! /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? sed无法执行扩展,awk能够执行此操作吗? Any help would be greatly appreciated. 任何帮助将不胜感激。 Thanks 谢谢

The simplest way to do this is with a for-loop over a glob pattern, then use paramater expansion to remove the prefix 最简单的方法是在全局模式上进行for循环,然后使用参数扩展来删除前缀

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 我们真的不需要sed:扩展模式和更多参数扩展

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. 如果看起来不错,请删除“ echo”。

Or, with the perl rename as suggested in the comments: 或者,按照注释中的建议使用perl rename

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

Remove "-n" if it looks good. 如果看起来不错,请删除“ -n”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM