Hi all,
I want to cut a column which match the regular expression "beta", if I don't know the column number?
cat test
alpha;beta;gamma
11;22;33
44;55;66
77;88;99
should be
command ....
beta
22
55
88
I tried the following command, but unfortunately the output is only the regular expression not all the column rows!
awk -F";" 'match($0,"beta",a){print a[0]}' test
beta
Any ideas how can I solve this??
use NR==1, then a for loop using NF as counter, loop through the fields one by one, checking for "beta". Get the value of the field number to a variable. After that print that value for every line.
I will try to create the loop!
Thanks
nawk -F";" '{
if(NR==1){
for(i=1;i<=NF;i++){
if($i=="beta"){
n=i
next
}
}
}
else{
print $n
}
}' a.txt
Thanks for you answer, but unfortunately I got the follow output:
~$ nawk -F";" '{if(NR==1){for(i=1;i<=NF;i++){if($i=="beta"){n=inext}}}else{print $n}}' test
11;22;33
44;55;66
77;88;99
awk -F";" 'NR==1{for(i=1;i<=NF;i++)if ($i==...){n=i}}{print ....}' file
please familiarize yourself with the awk language by reading the gawk manual, available online.
I solved this issue with the following script.
#!/bin/bash
#set -x
var=$(cat $2 | head -1 | sed 's/;/\n/g' | grep -n "$1" | cut -f1 -d":")
if [ -z $var ];then
echo "no string found"
else
cat $2 | cut -f$var -d";"
fi
however ghostdog74 I going to take your advice about awk!
If you have any tutorials or tips regarding awk then please send it to me!
Thanks in advance!