2

I have a text file contains:

台北市\\tai2bei3shi4 警察局\\jing3cha2ju2.

I want to delete everything starting from \\ and ending at the white space. The result looks like this:

台北市 警察局

How can I do it? Is there a one line command?

4

3 回答 3

1

这使用GNU sed有效:

sed 's/\\[^ ]*//g' <textfile>

Sed 的替换工作如下:s/regexp/replacement/

  • regexp部分是,这\\[^ ]*意味着“找到一个\和它后面的任何非空白字符”
  • replacement是空的,因为我们想用空替换匹配的regexp部分
  • g意味着应该在每一行上尽可能多地执行替换
于 2012-10-03T14:56:43.117 回答
0

如果您删除从 \\ 开始并以空格结尾的所有内容,您将得到

台北市警察局\\jing3cha2ju2.

不是

台北市 警察局

但如果你想得到台北市 警察局

sed -r 's/\\\\[^ ]+( |\.)//g' file.txt

产生以下输出:

台北市警察局

您可以通过添加将输出发送到第二个文件> file2.txt

\\\\ 你必须对两个角色进行转义,这就是为什么有四个角色

[^ ]+ 一系列不包括空格的字符

( |\.)空格或点(点必须转义)

-r 所以你不必转义方括号或括号

于 2012-10-03T20:44:07.473 回答
0

基于您的输入的 sed 行:

sed 's/[0-9a-zA-Z.\\\\]*//g' file

测试

kent$  echo "台北市\\tai2bei3shi4 警察局\\jing3cha2ju2."|sed 's/[0-9a-zA-Z.\\\\]*//g'
台北市  警察局
于 2012-10-03T21:11:02.877 回答