bashloopsunixcutunix-head

Cut command including a space which is confusing head command?


I am trying to use the output of a cut command into a head command to output a specific line. I find that if the number being fed into the head command 10+ it works fine. So I am wondering if the cut -c1-2 is including white space for the single digits that is tripping up the head command?

my code

#!/bin/bash
echo "Enter your name"
read input
cut -c5-19 filelist | grep -n "$input" | cut -c1-2 > cat

while read cat
do
head -$cat filelist | tail -1 > filelist2
done < cat

Any advice or suggestions will be greatly appreciated! Thank you :) Edit

FULLRanjit Singh   Marketing  Eagles       Dean Johnson   
FULLKen Whillans   Marketing  Eagles       Karen Thompson 
PARTPeter RobertsonSales      Golden TigersRich Gardener  
CONTSandeep Jain   President  Wimps        Ken Whillans   
PARTJohn Thompson  Operations Hawks        Cher           
CONTCher           Operations Vegans       Karen Patel    
FULLJohn Jacobs    Sales      Hawks        Davinder Singh 
FULLDean Johnson   Finance    Vegans       Sandeep Jain   
PARTKaren Thompson EngineeringVegans       John Thompson  
FULLRich Gardener  IT         Golden TigersPeter Robertson
FULLKaren Patel    IT         Wimps        Ranjit Singh   

This is 'filelist' The error I am getting is "head: invalid trailing option -- :" If I type in 'Patel' as the name, it works.


Solution

  • Answer to revised question

    Replace:

    cut -c5-19 filelist | grep -n "$input" | cut -c1-2 > cat
    

    With:

    cut -c5-19 filelist | grep -n "$input" | cut -d: -f1 >cat
    

    grep -n places a colon between the line number and the text of the line. So, it is natural to use a colon as field delimiter for cut and ask cut to return the first field.

    From what you have shown, the script can be further simplified to:

    read -p "Enter your name: " input
    linenum=$(cut -c5-19 filelist | grep -n "$input" | cut -d: -f1)
    head -$linenum filelist | tail -1 > filelist2
    

    Answer to original question

    Since you haven't shown us filelist, we can only guess at the problem. If you are right about filelist containing spaces, then this is the solution. Replace:

    head -$cat filelist | tail -1 > filelist2
    

    With:

    head -${cat## } filelist | tail -1 > filelist2
    

    The construction ${cat## } removes all leading spaces from the varialbe cat.