[英]how to use substr in awk?
I have strings that look like this我有看起来像这样的字符串
/foo/bar
/foo/bar/1
/foo/bar/baz
/foo/bar/baz/1
I want to be able to chop off the end only if it's a number.我希望只有当它是一个数字时才能切断结尾。 For example,
/foo/bar
stays the same, but /foo/bar/1
becomes /foo/bar
例如,
/foo/bar
保持不变,但/foo/bar/1
变为/foo/bar
How to I do this in awk?我如何在 awk 中做到这一点?
Using awk
, you can try it as:使用
awk
,您可以尝试如下:
awk '{sub(/\/[0-9]+$/,"");print}' filename
For your input output comes as:对于您的输入输出为:
/foo/bar
/foo/bar
/foo/bar/baz
/foo/bar/baz
If you want to use substr
function in awk:如果要在 awk 中使用
substr
函数:
awk '{line=substr($0,1,index($0,/[0-9]/)-2); if(length(line)==0)line=$0; print line}' filename
Using sed
, you can do it as:使用
sed
,您可以这样做:
while read line; do echo $line | sed 's/\/[0-9]\+$//'; done < filename
I guess your number is at the end of your expression.我猜你的号码在你的表达的末尾。 In that case the code below will work, if otherwise please let me know.
在这种情况下,下面的代码将起作用,否则请告诉我。
echo "/foo/bar/1" | awk -F"[0-9]+" '{print $1;}'
the code above will print: /foo/bar/
上面的代码将打印:
/foo/bar/
So many ways, but方法很多,但是
sub(/\/[0-9]+$/, "");
might be the easiest.可能是最简单的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.