简体   繁体   English

将grep输出放入循环变量中

[英]Put grep output inside variable from a loop

I have CentOS and this bash script: 我有CentOS和这个bash脚本:

#!/bin/sh
files=$( ls /vps_backups/site )
counter=0
for i in $files ; do
echo $i | grep -o -P '(?<=-).*(?=.tar)'
let counter=$counter+1
done

In the site folder I have compressed backups with the following names : 在站点文件夹中,我使用以下名称压缩了备份:

    site-081916.tar.gz
    site-082016.tar.gz
    site-082116.tar.gz
    ...

The code above prints : 081916 082016 082116 上面的代码打印:081916 082016 082116

I want to put each extracted date to a variable so I replaced this line 我想将每个提取的日期放入一个变量,所以我替换了这一行

echo $i | grep -o -P '(?<=-).*(?=.tar)'

with this : 有了这个 :

dt=$($i | grep -o -P '(?<=-).*(?=.tar)')
echo $dt

however I get this error : 但是我得到这个错误:

./test.sh: line 6: site-090316.tar.gz: command not found

Any help please? 有什么帮助吗?

Thanks 谢谢

您仍然需要$(...)内部的echo

dt=$(echo $i | grep -o -P '(?<=-).*(?=.tar)')

Don't use ls in a script. 不要在脚本中使用ls Use a shell pattern instead. 请改用壳模式。 Also, you don't need to use grep ; 另外,您不需要使用grep bash has a built-in regular expression operator. bash有一个内置的正则表达式运算符。

#!/bin/bash
files=$( /vps_backups/site/* )
counter=0
for i in "${files[@]#/vps_backups/site/}" ; do
  [[ $i =~ -(.*).tar.gz ]] && dt=${BASH_REMATCH[1]}
  counter=$((counter + 1))
done

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

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