johan
johan

Reputation: 45

Store in a variable a path read in a file (script shell)

I have a file with several path inside with the shape:

directory1/directory2/directory3

I would like to put one of these path inside a variable in a script shell, to use it as a path.

I tried :

name="`sed -n 2p file`"

But i cannot use a command like : cd "../$name". I have an error message saying this folder doesn't exist.

Do you have an idea how i can perform this on my script?

Upvotes: 0

Views: 78

Answers (2)

Nachiket Kate
Nachiket Kate

Reputation: 8571

use cut,

name=`cut -f1 -d "/" file`  # instead of f1 use f2 for directory2 and so on

like this,

[root@giam46 ~]# cat sample.txt
Desktop/MEF_R400
[root@giam46 ~]# name=`cut -f1 -d "/" sample.txt`
[root@giam46 ~]# echo $name
Desktop
[root@giam46 ~]# cd /root/${name}
[root@giam46 Desktop]# pwd
/root/Desktop
[root@giam46 Desktop]# cd ..
[root@giam46 ~]# pwd
/root
[root@giam46 ~]#

Upvotes: 1

Nik O'Lai
Nik O'Lai

Reputation: 3684

I think, it will be enough

name=`sed -n 2p file`

Upvotes: 1

Related Questions