Issue
I want to get abc/123/efg
from abc/123/efg/456
I try to get the first NF - 1
fields and concatenate them with /
.
echo abc/123/efg/456 | awk -F "/" 'BEGIN {OFS="/"} {for(i=1;i<=NF-1;i++) {var = var+$i} END {print var}'
However, it did not work as I expected.
What am I doing wrong?
Is there any way to do this more elegantly?
Solution
Here is my approach: Remove the last field. Yes, it is that easy. The code:
echo "abc/123/efg/456" | awk -F/ -vOFS=/ '{NF--; print}'
Notes
- The flag
-F/
specifies the input field separator - The flag
-vOFS=/
specifies the output field separator - The
NF--
statement decreases the number of fields by one - The
print
statement prints the whole record (line) after the removal of the last field
Answered By - Hai Vu Answer Checked By - Clifford M. (WPSolving Volunteer)