使用 sed 或 awk 将某些行中的换行符替换为空格

Replace newlines in some lines with spaces using sed or awk

我有一个包含一些事件的文本日志文件,我想修改它以提高可读性和打印格式。

我有:

$cat myfile 
foo bar foo bar

1.
1. foo bar
1:00

10.
3. foo bar
3:02

11.
4. foo
5:01

foobar foo

11.
foobar foo
3:48

2.
foobar foo
4:18

我想要的是:

$cat myfile
foo bar foo bar

1. 1. foo bar 1:00
10. 3. foo bar 3:02
11 4. foo 5:01

foobar foo

11. foobar foo 3:48
2. foobar foo 4:18

感谢任何帮助!谢谢!

Perl 来拯救:

perl -l -000 -pe 's/^|$/\n/g if 2 != s/\n/ /g' -- file
  • -000 打开 "paragraph mode" 读取由空行分隔的块中的输入
  • -l 从输入中删除输入分隔符并将其添加到输出
  • s/\n/ /g 用空格替换所有换行符(在一个块中)和 returns 替换次数
  • s/^|$/\n/g 在块的开头和结尾添加换行符

能否请您尝试关注,如果对您有帮助,请告诉我。

awk '/^[0-9]+\./{ORS=" "} !NF{ORS="\n"};1; END{ORS="";print RS}'   Input_file

输出如下。

foo bar foo bar

1. 1. foo bar 1:00
10. 3. foo bar 3:02
11. 4. foo 5:01
foobar foo

11. foobar foo 3:48
2. foobar foo 4:18

编辑: 添加非单线形式的解决方案,并在此处进行解释。

awk '
/^[0-9]+\./{  ##Checking condition here if any line starts from a digit(all together) and with a dot if yes then do following.
  ORS=" "     ##Setting value of ORS(output record separator) as space here.
}
!NF{          ##Checking if value of awk out of the box variable named NF value is NULL here, if yes then do following.
  ORS="\n"    ##Setting the value of ORS(output record separator) as new line here.
};
1;            ##By mentioning 1 here I am making condition TRUE here and not mentioning any action so by default print of current line will happen.
END{
  ORS="";     ##Setting value of ORS(output field separator) as NULL here.
  print RS    ##Printing value of RS which is new line by default.
}
' Input_file  ##Mentioning Input_file here.

您可以试试这个 awk 版本:

awk '/\.$/{printf "%s ", [=10=]; next} {print} your-file

你可以使用这个 sed

sed ':A;$bB;N;/\n$/!bA;:B;s/\n//g;s/\(^[^0-9]*$\)/\n&\n/;1,2s/^\n//' myfile

sed '
:A
$bB                     # jump to B if last line
N                       # add a new line in the pattern space
/\n$/!bA                # if this new line is empty, not return to A
:B
s/\n//g                 # remove all \n to get only one line
s/\(^[^0-9]*$\)/\n&\n/  # if the line not contain number add \n before and after
1,2s/^\n//              # remove the \n before the first line
' myfile

通过将记录设置为段落模式

awk -v RS=  '{=}1'

你会得到

foo bar foo bar
1. 1. foo bar 1:00
10. 3. foo bar 3:02
11. 4. foo 5:01
foobar foo
11. foobar foo 3:48
2. foobar foo 4:18

要添加额外的空行,需要添加一些内容

awk -v RS=  '{=; t=!/[0-9]\./; 
              if(NR>1 && t) print ""; 
              print; 
              if(t) print ""}'

获得

foo bar foo bar

1. 1. foo bar 1:00
10. 3. foo bar 3:02
11. 4. foo 5:01

foobar foo

11. foobar foo 3:48
2. foobar foo 4:18