我有一个包含 1000 行/条目的文本文件。这 1000 个条目对应于我的数据框的列名称。这些是需要添加到数据框中以进行模型开发的新功能。我的输入文本文件如下所示:
show temperature all#Total Numbers Approved#g2/3
show temperature all#Total Numbers Approved#g2/2
show temperature all#Total Numbers Approved#g2/4
show temperature all#Total Numbers Approved#g0/2
show temperature all#Total Numbers Sent#g1/2
show temperature all#Total Numbers Sent#g1/3
show temperature all#Total Numbers Sent#g1/1
formulastat gpucores all parameter function-frames#formula:1#gpucores:11
formulastat gpucores all parameter function-frames#formula:1#gpucores:10
formulastat gpucores all parameter function-frames#formula:2#gpucores:10
formulastat gpucores all parameter function-frames#formula:2#gpucores:11
formulastat gpucores all parameter function-frames#formula:0#gpucores:8
我希望为每行自动添加 '',删除换行符并在每行条目后添加逗号。预期输出如下:
'show temperature all#Total Numbers Approved#g2/3', 'show temperature all#Total Numbers Approved#g2/2', 'show temperature all#Total Numbers Approved#g2/4', 'show temperature all#Total Numbers Approved#g0/2', 'show temperature all#Total Numbers Sent#g1/2', 'show temperature all#Total Numbers Sent#g1/3', 'show temperature all#Total Numbers Sent#g1/1', 'formulastat gpucores all parameter function-frames#formula:1#gpucores:11', 'formulastat gpucores all parameter function-frames#formula:1#gpucores:10', 'formulastat gpucores all parameter function-frames#formula:2#gpucores:10', 'formulastat gpucores all parameter function-frames#formula:2#gpucores:11', 'formulastat gpucores all parameter function-frames#formula:0#gpucores:8'
答案1
# if you need the space after comma
$ seq 10 | perl -pe 's/.+/"$&"/; s/\n/, / if !eof'
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"
# if space isn't required
$ seq 10 | sed 's/.*/"&"/' | paste -sd,
"1","2","3","4","5","6","7","8","9","10"
如果您需要单引号而不是双引号,请在上述解决方案中使用\x27
而不是"
答案2
您可以使用 shell 循环轻松完成此操作。只需阅读这些项目,然后用引号将其打印出来。唯一棘手的事情是在除最后一个之外的所有内容之后打印“,”,或者在除第一个之外的所有内容之前打印“,”(事实证明这更容易)。
{
read item
printf "'%s'" "$item"
while IFS= read -r item; do
printf ", '%s'" "$item"
done
echo
} <infile.txt >outfile.txt
答案3
$ awk '{printf "%s\047%s\047", sep, $0; sep=", "} END{print ""}' file
'show temperature all#Total Numbers Approved#g2/3', 'show temperature all#Total Numbers Approved#g2/2', 'show temperature all#Total Numbers Approved#g2/4', 'show temperature all#Total Numbers Approved#g0/2', 'show temperature all#Total Numbers Sent#g1/2', 'show temperature all#Total Numbers Sent#g1/3', 'show temperature all#Total Numbers Sent#g1/1', 'formulastat gpucores all parameter function-frames#formula:1#gpucores:11', 'formulastat gpucores all parameter function-frames#formula:1#gpucores:10', 'formulastat gpucores all parameter function-frames#formula:2#gpucores:10', 'formulastat gpucores all parameter function-frames#formula:2#gpucores:11', 'formulastat gpucores all parameter function-frames#formula:0#gpucores:8'