Dom Brown
Dom Brown

Reputation: 201

cd won't work on this path. Any ideas?

In a section of a script I am writing, I output a list of paths into a temporary text file for use later with cd. I am using sed to replace spaces in directory names with '\ ' so that I also make the script work with spaces in dir names. My command is given below: cat temp.txt | sed 's/ /\\ /g' This has the desired output of replacing spaces with '\ ' but when I try to cd later it ignores the second word and says that example\ does not exist. Any ideas how to fix this?

My whole script is on pastebin here if you want to look at it: http://pastebin.com/6jmnKDAd

This is from a backup before I added sed

Upvotes: 0

Views: 385

Answers (4)

Micha Wiedenmann
Micha Wiedenmann

Reputation: 20863

Is there a need to use a temporary file or could you store the directories in an array:

dirs=()
dirs+=("/tmp/file A.txt")
dirs+=("/tmp/file B.txt")

for d in "${dirs[@]}"; do
  cd "$d"
done

Resources

Upvotes: 0

Vijay
Vijay

Reputation: 67301

You need to do this instead of cat temp.txt | sed 's/ /\\ /g'

perl -F"/" -ane 'foreach (@F){if(/ /){$_="\"".$_."\"";}}print join "/",@F;' temp.txt

also check here

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 247042

To complement Lorenzo's answer, if you have a bunch of newline-separated pathnames in a file:

while IFS= read -r path; do
    cd "$path"
    do stuff
done < temp.txt

It is critical to quote "$path" to prevent the shell's word splitting

Upvotes: 3

Lorenzo L
Lorenzo L

Reputation: 201

Try enclosing your variable within " " without escaping blanks.

cd "$mydir"

Upvotes: 3

Related Questions