0

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 '18 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 '18 at 7:37
  • What be the variable(s) that you want to assign to? – RudiC Aug 10 '18 at 8:38
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 '18 at 12:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.