删除txt中的特定字符

2024-05-23 22:45:46 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有下一个txt格式:

'20201': "a" ,
'20202': "e" ,
'20203': "i" ,
'20204': "o" ,
'20205': "u" ,
'20207': "ae" ,
'20209': "ai" ,
'20210': "ao" 

当四位数为0时,我想删除它。因此,预期产出为:

'2021': "a" ,
'2022': "e" ,
'2023': "i" ,
'2024': "o" ,
'2025': "u" ,
'2027': "ae" ,
'2029': "ai" ,
'20210': "ao" 

我在想:

awk -i inplace  ' { for ( i = 1; i <= NF; ++i ) {

    if ( $i == '0')
        r = 1

    
    }
  }}
1 ' example.txt ```
    

Tags: txtforifexample格式aiawkae
3条回答

对于简洁的GNUsed解决方案,这是可行的:

sed "s/^\(....\)0/\1/" example.txt

在这里,我们只匹配前5个字符——前4个字符是free&;第五个是零。对于任何匹配项,我们仅将前5个字符替换为前4个字符

如果要修改文件,可以使用sed的-i选项:

sed "s/^\(....\)0/\1/" -i example.txt

(注意-i将适用于许多系统,但不是所有系统;请参阅解决方法here

如果my子字符串是正数,请删除第四位数字(如果为零):

sed -e 's/\([0-9][0-9][0-9]\)0/\1/g' file

如果myword为正数,则删除第四位数字(如果为零):

sed -e 's/\b\([0-9][0-9][0-9]\)0\([0-9]*\)\b/\1\2/g' file

有了awk,您可以试着用GNUawk中显示的样本编写并测试以下内容吗

如果不使用字段分隔符,请尝试:

awk 'substr($0,5,1)==0{ $0=substr($0,1,4) substr($0,6) } 1'  Input_file

或者使用字段分隔符尝试以下操作:在这里只处理第一个字段

awk '
BEGIN{
  FS=OFS=":"
}
substr($1,5,1)==0{
  $1=substr($1,1,4) substr($1,6)
}
1
'  Input_file

若要将输出保存到输入_文件本身,请在对上述命令的输出满意后附加 > temp && mv temp Input_file

解释:添加上述内容的详细解释

awk '                             ##Starting awk program from here.
BEGIN{                            ##Starting BEGIN section of this program from here.
  FS=OFS=":"                      ##Setting FS and OFS as colon here.
}
substr($1,5,1)==0{                ##Checking condition if 5th character is 0 then do following.
  $1=substr($1,1,4) substr($1,6)  ##Setting sub string of 1st 4 characters then mentioning characters from 6th character to last of 1st field here.
}
1                                 ##1 will print current line.
' Input_file                      ##Mentioning Input_file name here.

相关问题 更多 >