Reputation: 49
I have a problem with awk processing simple thing. But not simple and clear for me. This is what I need to parse:
$ cat file
/dir1/dir11/file1
/dir10/dir103/file2
/dir2/dir21/dir221/file3
And what is desired for me, to have separated path to files (without file names), like:
/dir1/dir11
/dir10/dir103
/dir2/dir21/dir221
I have allready tried this:
$ cat file | awk -F"/" '{for (i=1;i<NF;i++) print $i}'
dir1
dir11
dir10
dir103
dir2
dir21
dir221
and this:
$ cat file | awk -F"/" '{for (i=1;i<NF;i++) printf $i}'
dir1dir11dir10dir103dir2dir21dir221
and best results :
$ cat file | awk -F"/" '{ $NF=""; print}'
dir1 dir11
dir10 dir103
dir2 dir21 dir221
But still missing /
within path.
Upvotes: 2
Views: 588
Reputation: 85865
You need to set the output field separator if you modify the record. I would just decrement the number of fields if you have GNU awk
:
$ awk '{NF--}1' FS='/' OFS='/' file
/dir1/dir11
/dir10/dir103
/dir2/dir21/dir221
Else just add OFS='/'
to your last command:
$ awk '{$NF=""}1' FS='/' OFS='/' file
Or with a simple substitution using sed
:
$ sed 's%/[^/]*$%%' file
/dir1/dir11
/dir10/dir103
/dir2/dir21/dir221
Upvotes: 0
Reputation: 77145
Here is another way with awk
:
awk '{sub(/\/[^/]+$/,"")}1' file
Output:
$ cat file
/dir1/dir11/file1
/dir10/dir103/file2
/dir2/dir21/dir221/file3
$ awk '{sub(/\/[^/]+$/,"")}1' file
/dir1/dir11
/dir10/dir103
/dir2/dir21/dir221
Upvotes: 0