user1253622
user1253622

Reputation: 227

AWK/bash how to include a filename in AWK

I have the following awk script:

#! /bin/awk -f

BEGIN { FS = ":" }

{ print $1 " "  $2 " "  $3 " " $4 " "  }

I want to code a bash script with "#! /bin/bash", but I need to include a file with it; as the program displays the files.

#! /bin/bash

awk -f, '
FILENAME= $1
BEGIN { FS = ":" }

{ print $1 " "  $2 " "  $3 " " $4 " "  }

'

In above code, I tried to include the file but it doesnt work ?

Upvotes: 0

Views: 8331

Answers (3)

ghoti
ghoti

Reputation: 46826

You don't actually need to use bash to pull in filename.

[ghoti@pc ~]$ cat text
one:two:three:four
cyan:yellow:magenta:black
[ghoti@pc ~]$ cat doit.awk
#!/usr/bin/awk -f

BEGIN { FS=":" }

{
  printf("%s %s %s %s\n", $1, $2, $3, $4);
}

[ghoti@pc ~]$ ./doit.awk text     
one two three four
cyan yellow magenta black
[ghoti@pc ~]$ 

But as Tim suggested, it's difficult to figure out what results you're looking for, based on what you've included in your question. Do you REALLY need to be running your awk script inside bash for other reasons? Do you need the actually file NAME to be available within your awk script?

The more detailed a question you provide, the more accurate the details in the responses will be.

Upvotes: 0

Tim Pote
Tim Pote

Reputation: 28029

It's hard for me to tell from the question, but I think what you want is

#!/usr/bin/env bash

awk -F, '
{ 
  #do stuff
}' "$1"

That will run awk on the file that you pass into the shell script.

However, if you're wanting script variable replacement inside of awk, you can escape out of the literal string to get variable replacement. For example:

#!/usr/bin/env bash

filename="$1"
awk -F, '
{ 
  print "'"$filename"'"
}' "$1"

will print out the filename you passed for as many lines as you have in the file. Note that this will cause awk to treat all of those variables as literal strings. So this would work as well:

#!/usr/bin/env bash

filename="$1"
awk -F, '
BEGIN {
  awksFileName="'"$filename"'"
}
{ 
  print awksFileName
}' "$1"

Upvotes: 0

DarkDust
DarkDust

Reputation: 92316

It's not quite clear what you want to pass here. Do you want a variable that gets a filename as value? The easiest way do that would be to use -v var=value:

#! /bin/bash

awk -v MYFILENAME="$1" '
BEGIN { FS = ":" }

{ print MYFILENAME " " $1 " "  $2 " "  $3 " " $4 " "  }
'

Note that FILENAME is a reserved variable, you cannot set it.

Or do you want to pass input files ? In that case you simply pass them past the program, as in:

#! /bin/bash

awk '
BEGIN { FS = ":" }

{ print MYFILENAME " " $1 " "  $2 " "  $3 " " $4 " "  }
' "$1"

The -f option is to include an awk script, btw. So -f, would ask AWK to include a file named ,.

On the shell level, be sure to always enclose the variables with "...", as in "$1" so you correctly handle filename with spaces.

Upvotes: 2

Related Questions