Difference between awk -FS and awk -f in shell scripting

I am new to shell scripting and I'm very confused between awk -FS and awk -f commands used. I've tried reading multiple pages on the difference between these two but was not able to understand clearly. Kindly help. Here is an example: Lets consider that a text file say, data.txt has the below details.

S.No Product Qty Price
1-Pen-2-10
2-Pencil-1-5
3-Eraser-1-2

Now, when i try to use the following command:

$ awk -f'-' '{print $1,$2} data.txt

I get the below output:

1 Pen
2 Pencil
3 Eraser

But when i use the command:

$ awk -FS'-' '{print $1,$2} data.txt

the output is:

1-Pen-2-10
2-Pencil-1-5
3-Eraser-1-2

I don't understand the difference it does using the -FS command. Could somebody help me out on what exactly happens between these two commands. Thanks!

2 Answers

You are more confused than you think. There is no -FS.

FS is a variable that contains the field separator.

-F is an option that sets FS to it's argument.

-f is an option whose argument is the name of a file that contains the script to execute.

The scripts you posted would have produced syntax errors, not the output you say they produced, so idk what to tell you...

4

-FS is not an argument to awk. -F is, as is -f.

The -F argument tells awk what value to use for FS (the field separator).

The -f argument tells awk to use its argument as the script file to run.

This command (I fixed your quoting):

awk -f'-' '{print $1,$2}' data.txt

tells awk to use standard input (that's what - means) for its argument. This should hang when run in a terminal. And should be an error after that as awk then tries to use '{print $1,$2}' as a filename to read from.

This command:

awk -FS'-' '{print $1,$2}' data.txt

tells awk to use S- as the value of FS. Which you can see by running this command:

awk -FS'-' 'BEGIN {print "["FS"]"}'
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like