How to grep a single field from a line?

hi,

i have a text file with some fields.
file.txt

aaa|bbb|ccc|1-sh|2-sh|5-sh
ddd|eee|fff|1-sh|4-sh

i am selecting a line using grep command using the combination of 1st 3 column.

grep "aaa|bbb|ccc" file.txt

output:
aaa|bbb|ccc|1-sh|2-sh|5-sh

now i want to cut a field from this line.
if i am passing 2 as a parameter to a program, then it should cut "2-sh", if i specify 5 then it should cut 5-sh and so on.

Hi,

Could you please use the following code.

echo "aaa|bbb|ccc|1-sh|2-sh|5-sh" | awk -F"|" '{print $5}'

Output will be as follows.

2-sh

kindly let me know if you have any queries for same.

Thanks,
R. Singh

Your specification is a bit difficult to interpret. If you, in a line that begins with "aaa|bbb|ccc", want that field that begins with your parameter value (2 or 5), try

awk '-F|' '/^aaa|bbb|ccc/ {for (i=4; i<=NF; i++) if ($i ~ "^"fn) print $i}' fn=2 file
2-sh

Try something like this

$ cat <<eof | awk -F"|" '/^aaa\|bbb\|ccc/{for(i=1;i<=NF;i++)if($i~search"-sh")print $i}' search=1
aaa|bbb|ccc|1-sh|2-sh|5-sh
ddd|eee|fff|1-sh|4-sh
eof     

1-sh
$ cat <<eof | awk -F"|" '/^aaa\|bbb\|ccc/{for(i=1;i<=NF;i++)if($i~search"-sh")print $i}' search=2
aaa|bbb|ccc|1-sh|2-sh|5-sh
ddd|eee|fff|1-sh|4-sh
eof

2-sh
$ cat <<eof | awk -F"|" '/^aaa\|bbb\|ccc/{for(i=1;i<=NF;i++)if($i~search"-sh")print $i}' search=5
aaa|bbb|ccc|1-sh|2-sh|5-sh
ddd|eee|fff|1-sh|4-sh
eof

5-sh

@RudyC I think you missed back slash

$ cat <<eof | awk -F"|" '/^aaa|bbb|ccc/{for(i=1;i<=NF;i++)if($i~search"-sh")print $i}' search=1
aaa|bbb|ccc|1-sh|2-sh|5-sh
ddd|eee|fff|1-sh|4-sh
aaa|1-sh
eof

1-sh
1-sh

$ cat <<eof | awk -F"|" '/^aaa\|bbb\|ccc/{for(i=1;i<=NF;i++)if($i~search"-sh")print $i}' search=1
aaa|bbb|ccc|1-sh|2-sh|5-sh
ddd|eee|fff|1-sh|4-sh
aaa|1-sh
eof

1-sh

@Akshay Hegde: Not needed for my mawk. But, doesn't hurt, either. Thanks for pointing out.

@ RudiC : I tried in gawk so posted..