用cat在file.txt中用空格来挣扎

时间:2013-10-10 12:40:52

标签: bash spaces cat

我试图从文件创建文件路径列表,但我似乎无法绕过文件路径中的空格。

    # Show current series list
    PS3="Type a number or 'q' to quit: "
    # Create a list of files to display
    Current_list=`cat Current_series_list.txt`

    select fileName in $Current_list; do
        if [ -n "$fileName" ]; then
            Selected_series=${fileName}
        fi
        break
    done 

Current_series列表中的文件路径为:/ Volumes / Lara的Hard Drive / LARA HARD DRIVE / Series / The Big Bang Theory 3 / The.Big.Bang.Theory S03E11.avi

/ Volumes / Lara的硬盘/ LARA HARD DRIVE / Series / nakitaS03E11.avi

所以我希望他们两个分别在我的列表中分别为1和2,但我得到以下结果。

1) /Volumes/Lara's      6) Big
2) Hard             7) Bang
3) Drive/LARA       8) Theory
4) HARD         9) 3/The.Big.Bang.Theory
5) DRIVE/Series/The    10) S03E11.avi
Type a number or 'q' to quit: 

2 个答案:

答案 0 :(得分:0)

你需要稍微欺骗一下:

# Show current series list
PS3="Type a number or 'q' to quit: "
# Create a list of files to display
Current_list=$(tr '\n' ',' < Current_series_list.txt)
IFS=, read -a list <<< "$Current_list"

select fileName in "${list[@]}"; do
     if [ -n "$fileName" ]; then
         Selected_series="${fileName}"
     fi
     break
done 

echo "you selected $fileName"

执行:

$ ./a
1) /Volumes/Lara's Hard Drive/LARA HARD DRIVE/Series/The Big Bang Theory3/The.Big.Bang.Theory S03E11.avi
2) /Volumes/Lara's Hard Drive/LARA HARD DRIVE/Series/nakitaS03E11.avi
Type a number or 'q' to quit: 2
you selected /Volumes/Lara's Hard Drive/LARA HARD DRIVE/Series/nakitaS03E11.avi

关键是你必须将文件转换为数组。

此部分将其转换为"string one", "string two"格式:

$ tr '\n' ',' < Current_series_list.txt 
/Volumes/Lara's Hard Drive/LARA HARD DRIVE/Series/The Big Bang Theory 3/The.Big.Bang.Theory S03E11.avi,/Volumes/Lara's Hard Drive/LARA HARD DRIVE/Series/nakitaS03E11.avi,

虽然这个基于上一步中设置的逗号分隔符在变量list中创建一个数组:

IFS=, read -a list <<< "$Current_list"

答案 1 :(得分:0)

您可以尝试将Current_series_list.txt的每一行分别读入数组元素,然后从展开的数组"${Current_array[@]}"中选择:

# Show current series list
PS3="Type a number or 'q' to quit: "
# Create an array of files to display
Current_array=()
while read line; do Current_array+=("$line"); done < Current_series_list.txt 

select fileName in "${Current_array[@]}"; do
    if [ -n "$fileName" ]; then
        Selected_series=${fileName}
    fi
    break
done