AWK相当于LTRIM函数在c [英] awk equivalent of LTRIM function in C

查看:175
本文介绍了AWK相当于LTRIM函数在c的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要从一个字符串中删除前导零。我发现有一个像LTRIM没有内置的功能在C

I need to delete leading 0s only from a string. I found that there is no in-built function like LTRIM as in C.

我在想下面的awk脚本做到这一点:

I'm thinking of the below AWK script to do that:

awk -F"," 'BEGIN { a[$1] }
   for (v in a) {
       {if ($v == 0) {delete a[$v]; print a;} else exit;}
   }'

但你猜我没有正确声明数组,它抛出错误。对不起新AWK编程。你可以帮我把它在一起。

But guess I'm not declaring the array correctly, and it throws error. Sorry new to AWK programming. Can you please help me to put it together.

推荐答案

使用 AWK 的要求:

#!/usr/bin/awk -f
/^0$/   { print; next; }
/^0*[^0-9]/ { print; next; }
/^0/    { sub("^0+", "", $0); print; next; }
        { print $0; }

这提供了不修剪纯0到的空字符串的,以及避免的非数字的字段的(可能)不希望的修整。如果是后者实际上期望的行为,第二个模式/动作可以被注释掉。在这两种情况下,取代是去,因为加入了编号,以一个非数字字段将产生错误的方式。

This provides for not trimming a plain "0" to an empty string, as well as avoiding the (probably) unwanted trimming of non-numeric fields. If the latter is actually desired behavior, the second pattern/action can be commented out. In either case, substitution is the way to go, since adding a number to a non-numeric field will generate an error.

输入:

0
0x
0000x
00012

输出:

0
0x
0000x
12

输出微调非数字字段:

Output trimming non-numeric fields:

0
x
x
12

这篇关于AWK相当于LTRIM函数在c的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆