简体   繁体   中英

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!

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...

-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"]"}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM