srinivasu u
srinivasu u

Reputation: 1463

forward slash replacement in awk

I started to learn awk. Here I am trying to produced a formatted list of all song albums in a directory which have many sub-directories(year ranges). But the last gsub replacement is not removing forward slash. I know it can be done using many ways using bash utilities like sed. But I would like to learn why this is not working in awk.

lst=$(mktemp)
find . | grep -vE "\.mp3|\.sh|\."$ > $lst #| tee $lst
gawk -F"/" '{
if(NF>2){
gsub(".tar.gz","",$3)
gsub(".zip","",$3)
gsub(".ZIP","",$3)
gsub("/","",$3)
print $3
}
else
print$0
}' $lst
exit 0

Upvotes: 1

Views: 7572

Answers (3)

Håkon Hægland
Håkon Hægland

Reputation: 40718

You can simplify your script (my opinion) as follows:

find . | awk '
!/(\.mp3|\.sh|\.)$/ {
    n=split($0,a,"/")
    if(n>2){
        sub(".tar.gz","",a[3])
        sub(".zip","",a[3])
        gsub(".ZIP","",a[3])
        print a[3]
    }
    else
        print $0
}'

Upvotes: 2

alvits
alvits

Reputation: 6758

You used "/" as a field separator therefore $3 will never have "/".

Upvotes: 2

Jotne
Jotne

Reputation: 41446

This works fine:

echo "test/more" | awk '{gsub("/","",$0)}1'
testmore

So it may be some other wrong in your code.

Post input data, and how you like your output data.

Try using regex.

echo "test/more" | awk '{gsub(/\//,"",$0)}1'
testmore

gsub(regexp, replacement [, target])

Upvotes: 2

Related Questions