Bash:用空行分隔文件并分配给列表
例如,我有一个文件Bash:用空行分隔文件并分配给列表,bash,list,awk,Bash,List,Awk,例如,我有一个文件 a b c d 我想把这些行的数据列出来。空行将是分隔符。所以上面的文件列表是 First element = a Second element = b c Third element = d 将空行替换为,,然后删除换行符: cat <file> | sed 's/^$/, /' | tr -d '\n' cat|sed's/^$/,/'| tr-d'\n 以下awk可以: awk 'BEGIN{RS="";ORS=",";FS="\n";OFS="
a
b
c
d
我想把这些行的数据列出来。空行将是分隔符。所以上面的文件列表是
First element = a
Second element = b
c
Third element = d
将空行替换为
,
,然后删除换行符:
cat <file> | sed 's/^$/, /' | tr -d '\n'
cat|sed's/^$/,/'| tr-d'\n
以下awk可以:
awk 'BEGIN{RS="";ORS=",";FS="\n";OFS=""}($1=$1)' file
这会在末尾添加一个额外的,
。您可以通过以下方式消除此问题:
awk 'BEGIN{RS="";ORS=",";FS="\n";OFS=""}
{$1=$1;s=s $0 ORS}END{sub(ORS"$","",s); print s}' file
但是现在发生了什么,通过做这个微小的修改来消除最后一个or
(即逗号),您必须将完整的内容存储在内存中。这样,您就可以通过将完整文件存储在内存中来完成更无聊、更不优雅的工作:
awk '{s=s $0}END{gsub(/\n\n/,",",s);gsub(/\n/,"",s); print s}' file
下面的sed执行完全相同的操作。将完整文件存储在内存中并进行处理
sed ':a;N;$!ba;s/\n\n/,/g;s/\n//g' <file>
这取决于你需要如何处理这些数据 使用perl,您可以使用一行程序:
$ perl -00 -lnE 'say "element $. = $_"' file.txt
element 1 = a
element 2 = b
c
element 3 = d
但是很明显,您需要以某种方式处理这些元素,我怀疑Perl不是您喜欢的
使用bash,您可以执行以下操作:
elements=()
n=0
while IFS= read -r line; do
[[ $line ]] && elements[n]+="$line"$'\n' || ((n++))
done < file.txt
# strip the trailing newline from each element
elements=("${elements[@]/%$'\n'/}")
# and show what's in the array
declare -p elements
如果你真的想说
第一个元素而不是元素1
,那么请享受这个练习:-)。awk脚本在最后一个数字后面加了一个逗号,
。@oliv,是的。如果文件中有字符串呢。我喜欢awk示例,但它假定numbers@RF你需要更具体一些。请更新您的问题以显示更多信息。添加一个,也就是说,一个可表示的输入,一个预期的输出,更重要的是,您自己尝试了什么。我问你这个问题,因为我目前不知道你的评论是什么意思,因为它不清楚。欢迎来到堆栈溢出!仅供将来参考。对不起,这不是StackOverflow的工作方式。形式为“我想做X,请给我提示和/或示例代码”的问题被认为是离题的。请访问并阅读,特别是阅读
elements=()
n=0
while IFS= read -r line; do
[[ $line ]] && elements[n]+="$line"$'\n' || ((n++))
done < file.txt
# strip the trailing newline from each element
elements=("${elements[@]/%$'\n'/}")
# and show what's in the array
declare -p elements
declare -a elements='([0]="a" [1]="b
c" [2]="d")'
$ awk -v RS= '{print "Element " NR " = " $0}' file
Element 1 = a
Element 2 = b
c
Element 3 = d