【发布时间】:2013-04-21 20:57:25
【问题描述】:
我想从文本文件中读取行并将它们保存在变量中。
cat ${1} | while read name; do
namelist=${name_list},${name}
done
文件如下所示:
David
Kevin
Steve
etc.
而我想得到这个输出
大卫、凯文、史蒂夫等
并将其保存到变量 ${name_list}
【问题讨论】:
我想从文本文件中读取行并将它们保存在变量中。
cat ${1} | while read name; do
namelist=${name_list},${name}
done
文件如下所示:
David
Kevin
Steve
etc.
而我想得到这个输出
大卫、凯文、史蒂夫等
并将其保存到变量 ${name_list}
【问题讨论】:
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 < file.txt 构造
name 的变量,但在代码中您使用的是i。我的目标是使用read -r 来防止 bash 在 ws 上拆分并一次读取一整行。
$ 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
【讨论】:
使用column 和sed:
namelist=$(column input | sed 's/\t/,/g')
【讨论】:
variable=`perl -lne 'next if(/^\s*$/);if($a){$a.=",$_"}else{$a=$_};END{print $a}' your_file`
【讨论】: