get the user input in awk

后端 未结 3 1997
余生分开走
余生分开走 2020-12-06 06:51

Is there any way to read the user input through the awk programming? I try writing a script to read a file which contained student\'s name and ID. I have to get the name of

相关标签:
3条回答
  • 2020-12-06 07:35

    Assuming the input file is formatted as:

    name<tab>id
    

    pairs and you want to print the line where the name in the file matches the user input, try this:

    awk '
    BEGIN { FS=OFS="\t"; printf "Enter name: " }
    NR == FNR { name = $0; next }
    $1 == name
    ' - file
    

    or with GNU awk you can use nextfile so you don't have to enter control-D after your input:

    awk '
    BEGIN { FS=OFS="\t"; printf "Enter name: " }
    NR == FNR { name = $0; nextfile }
    $1 == name
    ' - file
    

    Post some sample input and expected output if that's not what you're trying to do.

    0 讨论(0)
  • 2020-12-06 07:37

    I've tested with line

    "awk 'BEGIN{printf "enter:";getline name<"/dev/tty"} {print $0} END{printf "[%s]", name}' < /etc/passwd" 
    

    and for me is better solution and more readeable.

    0 讨论(0)
  • 2020-12-06 07:45

    You can collect user input using the getline function. Make sure to set this in the BEGIN block. Here's the contents of script.awk:

    BEGIN {
        printf "Enter the student's name: "
        getline name < "-"
    }
    
    $2 == name {
        print
    }
    

    Here's an example file with ID's, names, and results:

    1 jonathan good
    2 jane bad
    3 steve evil
    4 mike nice
    

    Run like:

    awk -f ./script.awk file.txt
    
    0 讨论(0)
提交回复
热议问题