sed:删除文件前n个字符中的十六进制字符

时间:2014-05-28 13:31:47

标签: regex bash sed

我的模式如下:

201404018^@133^@^@1^@^2^@31@1^@^32
20140401^@8133^@3^@0^@^22@1^@^3
201404^@018133^@10^@3^@^4@12^@^321
20140401813322^@97^@^@5^@^23
上面的

^@表示NUL字符(0x00),我想在前14个字符(日期时间)内删除它们,但保留其余部分。就像:

20140401813312^@31@1^@^32
20140401813330^@^22@1^@^3
20140401813310^@3^@^4@12^@^321
20140401813322^@97^@^@5^@^23

我尝试过sed 's/^[0-9]{0,13}\x00//g' - 但这确实没有做任何事情。

提前致谢!

3 个答案:

答案 0 :(得分:6)

Perl救援:

perl -pe 's/\x0// while ($i = index $_, "\x0") >= 0 and $i < 14' input-file

对于每一行,它在位置低于14时删除零字节。

答案 1 :(得分:3)

要尊重perl,回答只是因为你问过sed:

在GNU / any上,

sed -E ':a; s/^(.{,13})\x0/\1/; ta'

但处理nulls是GNU扩展。

答案 2 :(得分:0)

Choroba的Perl解决方案更好,但也可以像Bash一样在Bash中完成:

while read -r line; do
    count=0
    for i in $(seq 0 ${#line}); do
        case ${line:$i:1} in
            [\x00-\x7F])
                count=$((count+1))
                if [ $count -eq 14 ]; then
                    len=$i
                    break
                fi
                ;;
        esac
    done
    c1=${line:0:$len}
    c1=${c1//[^\x00-\x7F]/}
    c2=${line:$((len+1))}
    echo "$c1$c2"
done < file

输出:

2014040181331^@31@1^@^32
2014040181333^@^22@1^@^3
2014040181331^@3^@^4@12^@^321
2014040181332^@97^@^@5^@^23