将文本文件重新格式化为一个行字符串

时间:2014-08-08 10:08:39

标签: linux unix awk sed grep

这是我所拥有的示例文件

1321|4
512|2
1056|2
314|16
69|1
239|2
0|0
0|0
0|0
0|0
534|0

但我需要文件格式如下:

1321|4|512|2|1056|2|314|16|69|1|239|2|0|0|0|0|0|0|0|0|534|0

我试着用awk运气,但我没有得到可用的结果,以前从未使用过它,也无法将示例和手册变成工作代码。我怎样才能达到所需的格式?任何帮助都会很棒。

4 个答案:

答案 0 :(得分:1)

您可以使用此

sed ':a ; N ;s/\n/|/g ; t a '

说明

 t loop  -- Loop continued until the substitution false or EOF occur .
 N       -- Get the two lines and stored in the pattern space .

N获取两行并存储在模式空间中,因此模式空间有两行,如line1\nline2,然后替换执行\n|,如{{1}因此,具有一行和循环的模式空间继续然后获得另一行并执行替换。 一旦line1|line2创建了循环终止并打印模式空间。

答案 1 :(得分:1)

这应该做:

tr '\n' '|' < file; echo

或者这个:

awk -v ORS=\| '$1=$1 END {print RS}' file

答案 2 :(得分:1)

我不确定awk是这款指甲最好的锤子,但是

awk '{ printf("%s%s", sep, $0); sep = "|" }' sample.txt

应该这样做。

这里是评论中的Jotne改进版本,添加了最后一个换行符:

awk '{ printf("%s%s", sep, $0); sep = "|" } END { print "" }' sample.txt

答案 3 :(得分:0)

仅限Shell(尽管它确实需要一个子shell:

read -d '' -r -a lines < file
(IFS=\|; echo "${lines[*]}")
相关问题