We help IT Professionals succeed at work.

Awk (or Sed) to show current field number from the Field Seperator

genehackman
genehackman asked
on
Medium Priority
612 Views
Last Modified: 2013-12-26
How can I awk (or sed) something to do a search and print out the Field NUMBER (position in the line) when it finds a match?

Example File has 3 lines:

This is - a test file.
This is a - test file.
This is a test - file.

Objective:
Find the positions of the "-"

Desired Outcome:
3
4
5

I can grep, awk -F-, and sed to find them (and / or do other things), but thought awk would have had a variable like FS or something that might help out.

Thoughts?
Thank you,
Gene
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2006

Commented:
try grep -n

-n prints line number in file
CERTIFIED EXPERT
Top Expert 2006

Commented:
sorry my mistake, just reread your example, ignore what I wrote
CERTIFIED EXPERT
Top Expert 2006

Commented:
have a look at using index in AWK, I think that might be it
hopefully some other expert can help ya cos Im now off home
have a good evening, sorry about my cockup
awk '{for(n=1;n<=NF;n++){if($n=="-")print n}}' file

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Author

Commented:
That worked perfectly !
Thank you,
Gene
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.