Bit*_*Nix 6 sed awk perl text-processing
我正在寻找基于下一行的客场联系线。到目前为止,我看到的唯一方法是创建一个 shell 脚本,该脚本将逐行读取并按照以下方式执行某些操作:
while read line
if $line does not start with "," and $curr_line is empty
store line in curr_line
if $line does not start with "," and $curr_line is not empty
flush $curr_line to file
store $line in $curr_line
if $line starts with "," append to $curr_file, flush to file empty curr_line
done < file
Run Code Online (Sandbox Code Playgroud)
所以我试图了解是否可以通过 sed 甚至 grep 重定向来实现。文件的规则很简单。最多只有一行以“,”开头,需要附加到前一行。
前任:
line0
line1
line2
,line3
line4
line5
,line6
line7
,line8
line9
line10
line11
Run Code Online (Sandbox Code Playgroud)
结果文件将是
line0
line1
line2,line3
line4
line5,line6
line7,line8
line9
line10
line11
Run Code Online (Sandbox Code Playgroud)
我会做:
awk -v ORS= '
NR>1 && !/,/ {print "\n"}
{print}
END {if (NR) print "\n"}' < file
Run Code Online (Sandbox Code Playgroud)
也就是说,如果当前行不以 开头,则仅打印分隔前一行的换行符,
。
在任何情况下,我都不会使用while read
loop。
这是 的经典用例sed
,如Sed One-Liners Explained, Part I: File Spacing, Numbering and Text Conversion and Substitution , 40 中所述。如果前一行以等号“=”开头,则在前一行追加一行。(明显修改了,
for =
)
sed -e :a -e '$!N;s/\n,/,/;ta' -e 'P;D' file
line0
line1
line2,line3
line4
line5,line6
line7,line8
line9
line10
line11
Run Code Online (Sandbox Code Playgroud)
您需要做的就是 slurp 文件并删除逗号前的所有换行符:
$ perl -0777pe 's/\n,/,/g' file
line0
line1
line2,line3
line4
line5,line6
line7,line8
line9
line10
line11
Run Code Online (Sandbox Code Playgroud)