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
How to I do this in 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:
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.
Using
awk
, you can try it as:For your input output comes as:
If you want to use
substr
function in awk:Using
sed
, you can do it as: