I'm new to Linux, so this might be a relatively simple task but my research failed me. I want to write a awk script where it should iterate through a input file which has only one word per line and assign it to a variable, and I have to do some string operations on it. I'm quite confused with how to take the word on each line (by referencing the input file entered in the terminal) and assign it to a variable.

  • 2
    Did you already read the awk manual?
    – RalfFriedl
    Aug 10, 2018 at 6:19
  • This question would be much improved with examples of 1) the file you intend to parse, 2) what you're hoping the output will be like and 3) a sample of what you've already tried so far.
    – Shadur
    Aug 10, 2018 at 7:37
  • What be the variable(s) that you want to assign to?
    – RudiC
    Aug 10, 2018 at 8:38

1 Answer 1


If each line has a single word on it, awk would put that word in $1 ("the first field"). You can then extract it from there and put it in a variable if you like, with var = $1. Regardless, you can do any string operation that you wish by operating on $1 (or var, if you assigned the value to that variable).

For example, assuming each word looks like word=otherthing and we'd like to output only otherthing:

awk '{ split($1, a, "="); print a[2] }' infile

or shorter,

awk -F '=' '{ print $2 }' infile

$2 is the second field on each line, and with -F '=' we tell awk that the fields are delimited by =.

You don't mention what it is you need to do, so I won't give more examples.

You may also write this as a script that a user can call directly:

#!/usr/bin/awk -f

BEGIN { FS = "=" }

{ print $2 }

This would be saved in a text file, made executable (with chmod +x script.awk), and then a user could call it with

./script.awk infile

... assuming the #!-line pointed to your awk binary.

  • Thank You. The Script file worked for me. But I assigned like this var=$1.
    – user304716
    Aug 10, 2018 at 12:29
  • how do you specify the infile inside the script file itself?
    – ychaouche
    May 25, 2022 at 17:13
  • @ychaouche By taking the first or second command in this answer and making that into a shell script (which just means adding #!/bin/sh as the first line and making the file executable).
    – Kusalananda
    May 25, 2022 at 17:34
  • thanks @Kusalananda. I out there's another solution where you set ARGV[1] and ARGC to 2 inside the BEGIN block. Source
    – ychaouche
    May 26, 2022 at 11:56
  • @ychaouche If that works for you, then go with that. It's an unusual and awkward way to misuse the internal command line argument variables, and I would never suggest writing code like that.
    – Kusalananda
    May 26, 2022 at 12:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .