how to use substr in awk?

7.4k views Asked by At

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

How to I do this in awk?

3

There are 3 answers

5
Rakholiya Jenish On BEST ANSWER

Using awk, you can try it as:

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 '{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:

while read line; do echo $line | sed 's/\/[0-9]\+$//'; done < filename
0
Kristijan Iliev On

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/

0
ghoti On

So many ways, but

sub(/\/[0-9]+$/, "");

might be the easiest.