【问题标题】:Struggling with spaces in file.txt with cat用 cat 处理 file.txt 中的空格
【发布时间】:2013-10-10 12:40:51
【问题描述】:

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

    # 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

/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: 

【问题讨论】:

    标签: bash spaces cat


    【解决方案1】:

    你需要稍微欺骗一下:

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

    【讨论】:

    • 非常感谢,如何在将其解析为变量 Selected_series 时删除 "
    • 我刚刚注意到Current_list=$(tr '\n' ',' &lt; Current_series_list.txt) 就足够了。请检查我的更新答案
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-02
      • 2023-03-25
      • 2016-11-07
      • 1970-01-01
      • 1970-01-01
      • 2021-01-25
      相关资源
      最近更新 更多