Search a file and return the Kth word on the Nth line.
bashr s1.txt 3 1 Usage: bashr s1.txt 3 1 arg1 - input file name arg2 - line number (N, first lies is =1) arg3 - word number (N, first word is =1) % cat s1.txt 1.23 , here is extra stuff on the line I will ignore A Boot 17.333 This is line 4 % bashr s1.txt 3 1 Boot % bashr s1.txt 1 6 stuff Here is what I wrote this for: % cat My.egs mgp -radec=14.291777,52.974603,gc1,14.286354,52.738569,gc2,14.258120,52.896464,wf1,14.290218,52.823983,wf2 14.291777 52.974603 gc1 14.286354 52.738569 gc2 14.258120 52.896464 wf1 14.290218 52.823983 wf2 % bashr My.egs 3 2I have written much of this up in my bash basics documents, but showing the bashr source code may be useful here:
#!/bin/bash
# Jun2016 == find word K in a file (infile) on line N
# Check command line arguments
if [ -z "$1" ]
then
printf "Usage: bashr s1.txt 3 1 \n"
printf "arg1 - input file name\n"
printf "arg2 - line number (N, first lies is =1)\n"
printf "arg3 - word number (K, first word is =1)\n"
exit
fi
if [ -z "$2" ]
then
printf "arg2 - line number (N)\n"
exit
fi
if [ -z "$3" ]
then
printf "arg3 - word number (K)\n"
exit
fi
fin="$1"
nline="$2"
kword="$3"
i="0"
exec<$fin
while read -r line; do
i=$[$i+1]
# split (using white space) the line into array elements
# IFS=', ' read -r -a array <<< "$line"
IFS=' ' read -r -a array <<< "$line"
# assign names to some of the array values
word1="${array[0]}"
word2="${array[1]}"
word3="${array[2]}"
nn=$[$kword-1]
word="${array[nn]}"
# printf "\tline = $i nn = $nn Kth word = $word\n"
if [ $i = "$nline" ]
then
answer1="$word"
fi
done
printf "$answer1\n"