使用 sed 从文本文件中提取摩尔斯电码

Using sed to extract morse code from a text file

我有一个作业要使用 'sed' 从包含以下

的文本文件中提取摩尔斯电码(破折号和句号)
A test to see if the morse code can be removed from a file. .--- -. ..
This is a test --. -.- .-- .. -.. --- .- .. of sorts and so on. Let's see if the code snippets can be found.
Also can they be .- . -.- removed and yet leave the periods at the end
of sentences alone. ---- -. There are also hyphenated words like the
following: Edgar-Jones. -.

现在我可以使用 sed 删除所有字符 [a-z] 和 [A-Z],但问题是句子末尾的句点以及 Edgar-Jones 中的连字符都会被删除。我也找不到解决这些问题的方法...

任何帮助将不胜感激,谢谢

感谢大家的回答,每一个都有帮助。这是我一起去的

sed "s/[a-zA-Z][-.]//g;s/[a-zA-Z: ']*//g" file

它会找到字符后面的破折号或句点的实例,然后首先删除我遇到的问题。然后它会清理其余的字符、空格、冒号和撇号。

再次感谢!

这里有一个 awk 可以解决这个问题。

awk '{for (i=1;i<=NF;i++) if ($i!~/[a-zA-Z0-9]/) printf "%s ",$i;print ""}' file
.--- -. ..
--. -.- .-- .. -.. --- .- ..
.- . -.-
---- -.
-.

这个测试每个字段,如果它包含 a-z 不打印它。

或者正如 Glenn 评论的那样:

awk '{for (i=1;i<=NF;i++) if ($i~/^[.-]+$/) printf "%s ",$i;print ""}' file

这个 sed 单行代码应该可以完成这项工作:

extract morse code (dashes and periods)

在您的示例文件中:

sed "s/[a-zA-Z][-.]//g;s/[a-zA-Z: ']*//g" file

用你的文件测试:

kent$  cat f1
A test to see if the morse code can be removed from a file. .--- -. ..
This is a test --. -.- .-- .. -.. --- .- .. of sorts and so on. Let's see if the code snippets can be found.
Also can they be .- . -.- removed and yet leave the periods at the end
of sentences alone. ---- -. There are also hyphenated words like the
following: Edgar-Jones. -.

kent$  sed "s/[a-zA-Z][-.]//g;s/[a-zA-Z: ']*//g" f1
.----...
--.-.-.--..-..---.-..
.-.-.-
-----.
-.
sed 's/\(^\|[[:blank:]]\)[^[:blank:]]*[^-.[:blank:]][^[:blank:]]*/ /g' file 
               .--- -. ..
     --. -.- .-- .. -.. --- .- ..              
     .- . -.-         
    ---- -.       
   -.

那个正则表达式是:

  • 行首,或space
  • 一些非白色space 个字符
  • 后跟一个非白色字符space或莫尔斯字符
  • 后跟一些非白人space 字符

这会识别其中至少包含一个非莫尔斯字符的单词,然后将它们替换为单个 space。

使用 GNU grep 更简单,可惜你不能使用它:

grep -oP '(?<=^|\s)[.-]+(?=\s|$)' file
sed 's/\.$//
     s/\([^-[:space:].]\{1,\}[-.]\{0,1\}\)*//g
     s/\([[:space:]]\)\{2,\}//g
     ' YourFile
  • 将多空格替换为 1
  • posix 版本