假设我有下一个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 ```
发布于 2020-12-16 10:51:56
使用awk
,请您尝试使用GNU awk
中显示的示例进行以下、编写和测试。
没有字段分隔符,请尝试:
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
若要将输出保存到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.
发布于 2020-12-16 11:02:32
对于一个简洁的GNU sed
解决方案,这是可行的:
sed "s/^\(....\)0/\1/" example.txt
在这里,我们只匹配前5个字符--前4个是自由的,第5个是零。对于任何匹配项,我们只将前5个字符替换为前4个字符。
如果要修改文件的位置,可以使用sed的-i
选项:
sed "s/^\(....\)0/\1/" -i example.txt
(注意,-i
将适用于许多系统,但不是所有系统;参见这里)
发布于 2020-12-16 11:47:42
如果我的子字符串是正数,如果它是零,则删除第四个数字:
sed -e 's/\([0-9][0-9][0-9]\)0/\1/g' file
如果我的单词是一个正数,如果它是零,则删除第四个数字:
sed -e 's/\b\([0-9][0-9][0-9]\)0\([0-9]*\)\b/\1\2/g' file
https://stackoverflow.com/questions/65321755
复制相似问题