Q: How to write this script?

Hi there :rolleyes:

I have a folder called backup
it is path is: ~/backup

Inside this folder, there are four files:
~/backup/test1.cpp
~/backup/test2.cpp
~/backup/test3.cpp
~/backup/PATHS.TXT

The fourth file PATHS.TXT contains the original paths for the three files. This is the content of it:

[1]/home/user/Desktop/test1.cpp
[2]/home/user/Desktop/folder3/test2.cpp
[3]/home/user/Desktop/test3.cpp

I want to write a script that:
1) take a number from user ( 1, 2 or 3 )
2) store the original path of the selected file into a variable p
3) copy the selected file to path p ( its original location )

This is what I have done so far:

#check if there is a parameter or not
if [ $# = 0 ]
then
echo List of all files in backup system:
cat ~/backup/PATHS.TXT
else

# Take the line that contains the file's original path:
l=`grep \[$1\] ~/backup/PATHS.TXT`
echo $l

# Store the file's original path into variable p
#p=
#echo $p

# Copy the file to its original location:
#f=
#cp $f $p
#echo File $f restored sccussfully to its original location $p
fi

The problem is:
I don't know how to store the original path only without the '[#]' ?

Something like:

cat ~/backup/PATHS.TXT
read NUMBER

p=$(sed -n "/^\[$NUMBER\]/s/.*]//p" ~/backup/PATHS.TXT)
cp ~/backup/$(basename $p) $p

Try:

read var
awk -F"]" '/\['"$var"'\]/ { split($NF,A,"/"); print "cp -p ~/backup/"A[length(A)]" "$NF }' PATHS.TXT | sh

How about:

bpath=~/backup
while IFS="[]" read x nr p; do 
  if [ $nr -eq $1 ]; then
    cp -p $bpath/${p##*/} ${p%/*}
  fi
done<$bpath/PATHS.TXT

Thanks scottn, YOU ARE A LIFE SAVER :slight_smile:
This what I have done, and it runs without errors:

#check if there is parameters or not
if [ $# = 0 ]
then
echo List of all files in backup system:
cat ~/backup/EXT.DAT
else

# Store the file's original path into variable p
p=$( sed -n "/^\[$1\]/s/.*]//p" ~/backup/EXT.DAT)

# Take the name of the file and store it into variable f:
f=$( echo $p | awk 'BEGIN { FS = "\/"} ;{ print $NF }' )

# add the abso. path to ff:
ff=~/backup/$f

# copy ff to the original path p:
cp $ff $p
echo File $f restored sccussfully to its original location $p
fi

---------- Post updated at 05:03 AM ---------- Previous update was at 05:01 AM ----------

dennis.jacob & Scrutinizer
Thanks for your help, hope you all the best :slight_smile: