正则表达式搜索和替换 - 重新格式化名称

时间:2020-12-22 16:50:08

I have all the mobile phone contacts from a Samsung A411 in one large file, to be imported into a Samsung Galaxy S3 phone/contacts.

我将三星A411的所有手机通讯录放在一个大文件中,然后导入三星Galaxy S3手机/联系人。

There is just one field that I can't do a standard 'replace' with, using Kate. Here is what I need to do:

使用Kate只有一个我不能做标准'替换'的领域。这是我需要做的:

N:Mickey Mouse

N:米老鼠

to be replaced with ..

被替换为......

N:Mouse;Mickey;;;

N:鼠标;米奇;;;

2 个解决方案

#1


1  

Using sed:

使用sed:

sed -r 's/N:(\w*) (\w*)/N:\2;\1;;;/g' file.txt

Explanation of the s command used:

使用的s命令的说明:

s/
   N:      # literal string "N:"          ┐
   (       # begin of capture group       │
      \w   # any word character           │
        *  # ...repeated 0 or more times  ├ regex
   )       # end of capture group         │
           # literal " " (space)          │
   (\w*)   # same capture group as above  ┘
/
   N:      # literal string "N:"          ┐
   \2      # backreference to 2nd group   │
   ;       # literal ";"                  ├ replacement
   \1      # backreference to 1st group   │
   ;;;     # literal ";;;"                ┘
/
   g       # apply to all matches         ] flags

I used sed -r (extended regular expressions) in order to avoid escaping each bracket in the command for the sake of readability.

为了便于阅读,我使用了sed -r(扩展正则表达式)以避免转义命令中的每个括号。

#2


0  

The "N" record is fine now, and there is no "N" duplicate. However, the "FN" line has been replaced. The "FN" should not be modified at all.

“N”记录现在很好,并且没有“N”重复。但是,“FN”系列已被替换。根本不应修改“FN”。

To replace only lines that start with N:, insert a ^ (match the beginning of the line), i. e.

要仅替换以N:开头的行,插入^(匹配行的开头),i。即

sed -r 's/^N:…

#1


1  

Using sed:

使用sed:

sed -r 's/N:(\w*) (\w*)/N:\2;\1;;;/g' file.txt

Explanation of the s command used:

使用的s命令的说明:

s/
   N:      # literal string "N:"          ┐
   (       # begin of capture group       │
      \w   # any word character           │
        *  # ...repeated 0 or more times  ├ regex
   )       # end of capture group         │
           # literal " " (space)          │
   (\w*)   # same capture group as above  ┘
/
   N:      # literal string "N:"          ┐
   \2      # backreference to 2nd group   │
   ;       # literal ";"                  ├ replacement
   \1      # backreference to 1st group   │
   ;;;     # literal ";;;"                ┘
/
   g       # apply to all matches         ] flags

I used sed -r (extended regular expressions) in order to avoid escaping each bracket in the command for the sake of readability.

为了便于阅读,我使用了sed -r(扩展正则表达式)以避免转义命令中的每个括号。

#2


0  

The "N" record is fine now, and there is no "N" duplicate. However, the "FN" line has been replaced. The "FN" should not be modified at all.

“N”记录现在很好,并且没有“N”重复。但是,“FN”系列已被替换。根本不应修改“FN”。

To replace only lines that start with N:, insert a ^ (match the beginning of the line), i. e.

要仅替换以N:开头的行,插入^(匹配行的开头),i。即

sed -r 's/^N:…