我有一个文本文件,其中包含以下格式的数据。
1^0^this is test file line1^
2^1^this is test file line2^
3^1^this
is
test
file line3^
4^1^this
is
file line4^
直到下一行以^结尾,它需要附加前一行
输出:
1^0^this is test file line1^
2^1^this is test file line2^
3^1^this is test file line3^
4^1^this is file line4^
根据行结尾处理输出记录分隔符(ORS
)的值。
$ awk '{ORS=/\^$/?"\n":" "}1' file
1^0^this is test file line1^
2^1^this is test file line2^
3^1^this is test file line3^
4^1^this is file line4^
一个便宜又简单的bash脚本。它不是寻找尾随胡萝卜,而是寻找领先数字和胡萝卜。
#!/bin/bash
filename=$HOME/asdf.txt
prevLine=""
while IFS= read -r var
do
if [[ $var =~ ^[0-9]{1}\^.*$ ]]
then
echo "$prevLine"
prevLine=""
prevLine="$var"
else
prevLine+=" $var"
fi
done < "$filename"
echo "$prevLine"
使用GNU sed 4.2(支持-z选项),您可以使用
sed -rz 's/([^^])\n/\1/g' file
您可以使用较旧的sed
tr "\n" "\r" < file | sed -r 's/([^^])\r/\1/g' | tr "\r" "\n"
编辑:当你想要连接线之间的空格时,使用
sed -rz 's/([^^])\n/\1 /g' file
另一个sed,使用鲜为人知的保持空间:
$ sed -ne '/[^^]$/{H;d}; {H;g;s/\n/ /g;p;s/.*//;h}' test.txt;
^1^0^this is test file line1^
^2^1^this is test file line2^
^3^1^this is test file line3^
^4^1^this is file line4^
基本上:如果当前行(模式空间)没有以^结尾,则将其附加到保留空间并继续下一行。否则,再次将当前行附加到保留空间,然后用保留空间替换当前模式空间,处理H
添加的换行符,并打印结果。然后清空保持空间以准备下一行序列(不幸的是,在一步中似乎没有真正容易做到最后一点)
笔记:
s/.*//
替换z
。