molni
molni

Reputation: 49

awk line processing $NF

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

Answers (3)

Chris Seymour
Chris Seymour

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

jaypal singh
jaypal singh

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

anubhava
anubhava

Reputation: 785631

This awk should work:

awk 'BEGIN{FS=OFS="/"} {$NF=""}'1 file

Upvotes: 1

Related Questions