Brian
Brian

Reputation: 1667

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

How to I do this in awk?

Upvotes: 1

Views: 8262

Answers (3)

Rakholiya Jenish
Rakholiya Jenish

Reputation: 3223

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

Upvotes: 2

ghoti
ghoti

Reputation: 46886

So many ways, but

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

might be the easiest.

Upvotes: 0

Kristijan Iliev
Kristijan Iliev

Reputation: 4987

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/

Upvotes: 0

Related Questions