如何在 Linux 上将句子放在不同的行上

Anu*_*Anu 7 bash text-processing

我有一项任务是将句子放在单独的行中的文本文件中。像这样的东西几乎有效:

cat file.txt | tr '.' '\n'
Run Code Online (Sandbox Code Playgroud)

但我不想在我的句子中丢失点、问号和感叹号。我怎样才能使这项工作?

ter*_*don 17

如果没有看到您的数据的实际示例,我无法确定,但您可能正在寻找的是在每次出现.,!和后添加一个换行符?。我不知道您想如何处理分号 ( ;),因为它们并没有真正标记句子的结尾。随你(由你决定。

无论如何,您可以尝试sed

$ echo 'This is a sentence! And so is this. And this one?' | 
    sed 's/[.!?]  */&\n/g' 
This is a sentence! 
And so is this. 
And this one?
Run Code Online (Sandbox Code Playgroud)

s///是替换操作符。它的一般格式是s/pat/replacement,它将替换patreplacement. 将g在年底使它运行中出现的所有置换pat。没有它,它会停在第一个。这&是一个特殊的sed结构,意思是“任何匹配的”。所以,在这里我们用匹配的任何内容和换行符替换., !, 或?中的任何一个。

如果您的文本可以包含诸如 的缩写e.g.,您可能只想在下一个字母是大写时替换:

$ echo 'This is a sentence! And so is this. And this one? Negative, i.e. no.' | sed 's/\([.!?]\) \([[:upper:]]\)/\1\n\2/g' 
This is a sentence!
And so is this.
And this one?
Negative, i.e. no.
Run Code Online (Sandbox Code Playgroud)

请注意,这不会Dr. Jones said hello.正确处理句子,因为它会假设.afterDr定义了一个句子,因为下一个字母是大写的。然而,我们现在接近的复杂程度远远超出了简单的问答格式,实际上需要一个成熟的自然语言解析器。

  • @don_crissti 该死,我什至没有考虑过缩写。您可以执行类似 `sed 's/\([.!?]\) \([[:upper:]]\)/\1\n\2/g'` 之类的操作,以便仅在下一个字符是大写字母。 (2认同)

Sté*_*las 6

尝试:

sed -e :1 -e 's/\([.?!]\)[[:blank:]]\{1,\}\([^[:blank:]]\)/\1\
\2/;t1'
Run Code Online (Sandbox Code Playgroud)

在像这样的输入上:

Sentence 1. Sentence 1.2? Sentence 2!? Sentence 3.
Sentence 4... Sentence 5.
Run Code Online (Sandbox Code Playgroud)

它给:

Sentence 1.
Sentence 1.2?
Sentence 2!?
Sentence 3.
Sentence 4...
Sentence 5.
Run Code Online (Sandbox Code Playgroud)

(并且是 POSIX)。


Arc*_*mar 1

尝试:

awk -F. '{ for (i=1;i<=NF;i++) printf "%s.\n",$i ;} ' < input_file > output_file
Run Code Online (Sandbox Code Playgroud)

在哪里

  • awk 使用.(点) 作为分隔符,
  • 并循环每个字段,打印行,一个点换行