【问题标题】:read line from file and save them in a comma separated string to a variable从文件中读取行并将它们以逗号分隔的字符串保存到变量中
【发布时间】:2013-04-21 20:57:25
【问题描述】:

我想从文本文件中读取行并将它们保存在变量中。

  cat ${1} | while read name; do

  namelist=${name_list},${name}

  done

文件如下所示:

David

Kevin

Steve
etc.

而我想得到这个输出

大卫、凯文、史蒂夫等

并将其保存到变量 ${name_list}

【问题讨论】:

    标签: bash variables cat


    【解决方案1】:
    name_list=""
    for name in `cat file.txt`
       do VAR="$name_list,$i"
    done
    

    编辑:此脚本在 name_list 的开头留下一个“,”。有很多方法可以解决这个问题。例如,在 bash 中这应该可以工作:

    name_list=""
    for name in `cat file.txt`; do
       if [[ -z $name_list ]]; then
          name_list="$i"
       else
          name_list="$name_list,$i"
       fi  
    done
    

    重新编辑:因此,感谢 Fredrik 的合法投诉:

    name_list=""
    while read name
    do 
      if [[ -z $name_list ]]; then
          name_list="$name"
       else
          name_list="$name_list,$name"
       fi
    done < file.txt
    

    【讨论】:

    • 不要为此使用cat,尤其是在反引号中!正确的解决方案是使用while read...; do ...; done &lt; file.txt 构造
    • 首先,您正在使用外部程序 (cat) 来完成 bash 完全能够自行处理的事情。其次,在这里,反引号是非常危险的,除非您知道反引号的结果将小于或等于您的 shell 可以接受的命令行的长度。第三,你在浪费一个进程。
    • 看起来更好,如果您也修复引号,我什至会投票 :-) 如果输入名称包含空格,它将失败...
    • 即使名称包含空格,它也适用于我:P 你能帮我解决它,所以我明白你的意思吗?
    • 如果它对您有用,那么您就不能使用您发布的代码:-) 您读入了一个名为name 的变量,但在代码中您使用的是i。我的目标是使用read -r 来防止 bash 在 ws 上拆分并一次读取一整行。
    【解决方案2】:

    命令:

    $ tr -s '\n ' ',' < sourcefile.txt             # Replace newlines and spaces with [,]
    

    这可能会返回 , 作为最后一个字符(也可能是第一个字符)。 去除逗号并返回令人满意的结果:

    $ name_list=$(tr -s '\n ' ',' < sourcefile.txt)      # store the previous result
    $ name_list=${tmp%,}                                 # shave off the last comma
    $ name_list=${tmp#,}                                 # shave off any first comma
    


    编辑

    此解决方案的运行速度提高了 44%,并在所有 Unix 平台上产生一致且有效的结果。

    # This solution
    python -mtimeit -s 'import subprocess' "subprocess.call('tmp=$(tr -s "\n " "," < input.txt);echo ${tmp%,} >/dev/null',shell = True)"
    100 loops, best of 3: 3.71 msec per loop
    
    # Highest voted:
    python -mtimeit -s 'import subprocess' "subprocess.call('column input.txt | sed "s/\t/,/g" >/dev/null',shell = True)"
    100 loops, best of 3: 6.69 msec per loop
    

    【讨论】:

      【解决方案3】:

      使用columnsed

      namelist=$(column input | sed 's/\t/,/g')
      

      【讨论】:

        【解决方案4】:
        variable=`perl -lne 'next if(/^\s*$/);if($a){$a.=",$_"}else{$a=$_};END{print $a}' your_file`
        

        【讨论】:

          猜你喜欢
          • 2023-01-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-07-10
          • 2021-03-31
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多