将grep输出从循环中放入变量中。

时间:2022-05-29 14:06:23

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文件夹中,我有以下名称的压缩备份:

    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

谢谢

2 个解决方案

#1


2  

you still need the echo inside the $(...):

您仍然需要$(…)中的echo:

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

#2


1  

Don't use ls in a script. Use a shell pattern instead. Also, you don't need to use grep; bash has a built-in regular expression operator.

不要在脚本中使用ls。使用shell模式。另外,您不需要使用grep;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

#1


2  

you still need the echo inside the $(...):

您仍然需要$(…)中的echo:

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

#2


1  

Don't use ls in a script. Use a shell pattern instead. Also, you don't need to use grep; bash has a built-in regular expression operator.

不要在脚本中使用ls。使用shell模式。另外,您不需要使用grep;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