1

I have a large file that I split with awk, using the last column as the name for the new files, but one of the columns include a "/", which gives can't open error.

I have tried make a function to transform the name for the file but awk don't use it when I run it, maybe a error from part:

tried_func() {
 echo $1 | tr "/" "_"
}


awk -F ',' 'NR>1 {fname="a_map/" tried_func $NF".csv"; print >> fname; 
close(fname)}' large_file.csv

Large_file.csv

A,        row,    I don't,  need
plenty,   with,   columns,  good_name
alot,     off,    them,     another_good_name
more,     more,   more,     bad/name

expected res:

list of file i a_map:

  • good_name.csv
  • another_good_name.csv
  • bad_name.csv

actual res:

awk: can't open file a_map/bad/name.csv

Don't need to be a function, if I can just skip the "/" in awk that is fab too.

Elmseld
  • 83
  • 12
  • As an aside, you mean `echo "$1"`. See also https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable – tripleee Jan 29 '19 at 11:15

1 Answers1

2

Awk is not part of the shell, it's an independent programming language, so you can't call shell functions that way. Instead, just do the whole thing within awk:

$ awk -F ',' '
NR>1 {
    gsub(/\//,"_",$NF)          # replace /s with _s 
    fname="a_map/" $NF ".csv"
    print >> fname
    close(fname)
}' file
James Brown
  • 36,089
  • 7
  • 43
  • 59
  • 1
    Thanks, I hoped it was something easy like that! Works like a charm! Didn't know it was its own language either! Good to know since it's awesome for what I do. – Elmseld Jan 29 '19 at 12:40