UNIX / Linux Shell脚本:从文本中删除变体形式的表情符号

问题描述

考虑您正在使用默认字符集为UTF-8的Linux / UNIX shell:

$ echo $LANG
en_US.UTF-8

您有一个文本文件emoji.txt,该文件以UTF-8编码:

$ file -i ./emoji.txt
./emoji.txt: text/plain; charset=utf-8

此文本文件包含一些表情符号和变体形式的转义序列:

$ cat     ./emoji.txt
Standard ☁
Variant form ☁️
$ uni2ascii -a B -q ./emoji.txt
Standard \x2601
Variant form \x2601\xFE0F

您要删除两个表情符号,包括该变体形式字符(\ xFE0F),因此输出应为

Standard 
Variant form 

您将如何做?

更新。这个问题不是关于如何删除每一行最后一个单词的问题。想象一下emoji2.txt,其中包含带有许多表情符号字符的大文本;并且其中一些后面是变体形式序列。

解决方法

使用GNU sedbash

  sed -E s/$'\u2601\uFE0F?'//g emoji.txt
,

将Unicode文本文件转换为ASCII,并删除由ASCII字符表示的Unicode字符,然后再次将其转换为UTF-8:

$ uni2ascii -q ./emoji.txt | sed "s/ 0x2601\(0xFE0F\)\?//g" | ascii2uni -q
Standard 
Variant form 
$
,

awk打印除最后一个字段以外的所有内容:

$ awk '/^Standard/ || /^Variant form/ { $(NF)="" }1' emoji.txt
Standard
Variant form

注意:此特定解决方案会将字段分隔符(空白)留在输出行的末端;如果您想剥离尾随的空白,可以通过管道传送到sedtr等...,或者让awk遍历字段1到(NF-1)并通过{{ 1}}

,

您可以使用awk,如下所示:

$ cat emo.ascii 
Standard \x2601
Variant form \x2601\xFE0F
$ ascii2uni -a B emo.ascii                                  
Standard ☁
Variant form ☁️
3 tokens converted # note: this is stderr
$ ascii2uni -a B emo.ascii | awk -F' ' '{NF--}1' | cat -A 
3 tokens converted # note: this is stderr
Standard$
Variant form$

NF--将减少awk中的字段数,从而有效地删除最后一个字段。 1的计算结果为true,这会使awk打印修改后的行。

(此处使用cat -A只是为了显示没有剩余的不可见字符)

,

使用nkf命令。 nkf -s尝试将字符编码转换为不支持表情符号的Shift-jis。因此,表情符号和转义序列将消失。最后,使用nkf -w将输入还原为UTF-8。

$ cat emoji.txt | nkf -s | nkf -w
Standard
Variant form

$ cat emoji.txt | nkf -s | nkf -w | od -tx1c
0000000  53  74  61  6e  64  61  72  64  20  0a  56  61  72  69  61  6e
          S   t   a   n   d   a   r   d      \n   V   a   r   i   a   n
0000020  74  20  66  6f  72  6d  20  0a
          t       f   o   r   m      \n
0000030

我认为ruby可能有用。因为\p{Emoji}与表情符号匹配。但是它仍然是转义序列。

$ ruby -nle 'puts $_.gsub!(/\p{Emoji}/,"")' emoji.txt
Standard
Variant form ️

$ ruby -nle 'puts $_.gsub!(/\p{Emoji}/,"")' emoji.txt | od -tx1c
0000000  53  74  61  6e  64  61  72  64  20  0a  56  61  72  69  61  6e
          S   t   a   n   d   a   r   d      \n   V   a   r   i   a   n
0000020  74  20  66  6f  72  6d  20  ef  b8  8f  0a
          t       f   o   r   m           217  \n
0000033

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...