3

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 2

7

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you! i think i understood this concept very badly. my bad. thanks for the clarification. Will work on it.
Technically -FS'-' is the same as -F "S-". So, echo "QRS-TUV" | awk -FS'-' '{print $1, $2}' outputs QR TUV
this was what my doubt was too. but when i try to use echo "ABC-DEF" | awk -FS'-' '{print $1,$2}' , I get ABC-DEF only
@Dev that would be the expected output since S- (as stored in FS) does not occur anywhere in your input so it only has 1 field so $1 is ABC-DEF. If you check the output you file a blank char added to the end of the line - that's the output field separator (OFS) before the null string represented by $2. btw wrt your incorrect use of the word doubt - the correct English would be thought or expectation or similar. doubt is when you think negatively about something.
3

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

Thank you! my bad. need to work on this concept more. thanks for the clarification. Will work on it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.