2013-04-21 37 views

回答

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 

重新編輯:所以,這要歸功於弗雷德裏克的合法投訴:

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

不使用'cat'對於這一點,尤其不要在反引號!正確的解決方案是使用'while read ...;做...;完成 2013-04-21 21:17:57

+0

這樣使用貓有什麼問題? – blue 2013-04-21 21:21:29

+1

首先,你正在使用一個外部程序(cat)來進行某些bash的操作,它本身是完全有能力的。其次,在這裏,反引號是非常危險的,除非你知道反引號的結果將小於或等於你的shell命令行可以接受的時間長度。第三,你正在浪費一個過程。 – 2013-04-21 21:28:38

2

命令:

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

這可能會返回一個,作爲最後一個字符(可能是第一個字符)。 刮鬍子逗號(S),並返回一個令人滿意的結果:

$ 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 
0
variable=`perl -lne 'next if(/^\s*$/);if($a){$a.=",$_"}else{$a=$_};END{print $a}' your_file` 
1

使用columnsed

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