为文件中的空格而苦苦挣扎.txt与猫



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

    # 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's Hard Drive/LARA HARD DRIVE/SERIES/The Big Bang Theory 3/The.Big.Bang.Theory S03E11.avi

/卷/劳

拉的硬盘/劳拉硬盘/系列/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: 

你需要稍微欺骗一下:

# 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"

您可以尝试将每行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 

最新更新