Niladri Banerjee
Niladri Banerjee

Reputation: 1

Unix Shell Script - AWK delimiter issue

I have following lines in a file. Please note I have intentionally kept the extra hash between 2 and 0 in the 2nd line. File name : test.txt

Name#|#Age#|#Dept  
AC#|#2#0#|#Science  
BC#|#22#|#Commerce

I am using awk to get the data in Dept column

awk -F "#|#" -v c="Dept" 'NR==1{for (i=1; i<=NF; i++) if ($i==c){p=i; break}; next} {print $p}' "test.txt" >> result.txt

The result.txt shows me the following

|  
Commerce

The first line is coming as pipe because if the extra # in the first line. Can anyone help on this

Upvotes: 0

Views: 36

Answers (2)

CWLiu
CWLiu

Reputation: 4043

If you desire to extract Dept in your content, here's a good choice you can choose from,

 awk -F'#' 'NR>1{print $NF}' test.txt

output:

Science  
Commerce

Upvotes: 0

l&#39;L&#39;l
l&#39;L&#39;l

Reputation: 47274

Currently the meaning of the delimiter set is: match # or #. The pipe | character in this case acts as an OR statement; instead try using:

awk -F '#[|]#' ...

Putting | into a character class [ ... ] awk will match it literally.

Upvotes: 1

Related Questions