简体   繁体   中英

Put grep output inside variable from a loop

I have CentOS and this bash script:

#!/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

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. Use a shell pattern instead. Also, you don't need to use grep ; bash has a built-in regular expression operator.

#!/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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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