oussama kamal oussama kamal - 3 months ago 19
Linux Question

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

Answer

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

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