How to find the column number in a text file using unix commands

Suppose I have a text file with six columns below

a|b|c|d|e|f

I know there is a 'd' character somewhere in the file, but I want to know that there is no column for it

I used the following command

awk 's=index($0,"d"){print "position="s}' filename

but he also considers delimiters that I don’t need .... I want the output to be 4 in case of "d"

+4
source share
2 answers

define "|" as a Seperator entry, and use the NR variable in awk:

awk -v RS="|" '/^d$/{print NR;}' filename

change ^d$to what you want to combine.

+6
source

With awk you can:

awk -v val='d' -F '|' '{for (i=1; i<=NF; i++) if ($i==val) {print i} }' file
4
+6
source

Source: https://habr.com/ru/post/1540011/


All Articles