• Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Staging Ground badges

Earn badges by improving or asking questions in Staging Ground.

set multiple variables from one awk command?

This is a very common script:

However I dont like this, especially when there are more fields to parse. I guess there should be a better way like:

(var1,var2)=`echo ${teststr} | awk '{print $1 $2}' (in my imagination)

Is that so? Thanks for help to improve effeciency and save some CPU power.

X.M.'s user avatar

  • 2 read -r a b < <(awk '{print $1, $2}' <<< "hello world") –  user12007102 Commented Oct 15, 2021 at 21:54

4 Answers 4

This might work for you:

Will output:

Max MacLeod's user avatar

  • 1 Thanks to remind me for bash arries. This is the solution. One can also write like this: var=( echo ${blabla} | awk -F"_" '{print $1 " " $3}' )... –  X.M. Commented Mar 2, 2012 at 8:28
  • Nice! Use of parentheses is key. –  Max MacLeod Commented Sep 28, 2023 at 13:36

Yes, you can, but the best practice is to use the awk way to pass variables to awk .

Example using shell script variables

Example using environmental variables

It's possible to use script and environmental variables at the same time

You may find bash tricks to circumvent the awk way to do it, but it's not safe.

Explanation and more examples

Awk works this way, because it's a programming language by itself and has it's own way to use variables 'inside' awk statements.

By ' inside ' i mean the part between the single quotes .

Let's see an example, where we turn off DHCP in a config file, all done using variables in a shell script. I'm going to explain the last line of code.

The script isn't optimal, it's main purpose is to use script variables. Explaining how the script does its job is out of scope of this answer, the focus is on explaining the use of variables.

Let's break this last line up to pieces for explanation.

awk -v awkDHCP_LINE="$DHCP_LINE" -v awkSPACES="$SPACES"

This part above assigns the value of DHCP_LINE script variable to the awkDHCP_LINE awk variable and the the value of SPACES script variable to the awkSPACES awk variable.

Please note, that the SPACES variable is passed to awk for the sake of showing how to pass multiple variables only; the awk command doesn't process it.

'FNR==awkDHCP_LINE {sub("dhcp4: yes", "dhcp4: no")}'

This one above is the ' inside ' part of awk where the variable(s) passed to awk can be used.

$CONFIG_FILE

This part is outside awk, a generic script variable is used to specify the file that should be processed.

I hope this clears things a bit :)

Note: if you have lots of variables to pass, the solution provided by @potong may prove a better approach depending on your use case.

linux64kb's user avatar

  • 1 Is this answer about how to pass variables in to awk? The question is about how to assign values from the output of awk to bash variables. –  Jim Holmes Commented May 3, 2023 at 11:29

You can also use shell set builtin to place whitespace seperated (or more accurately, IFS seperated) into the variables $1 , $2 and so on:

Omer Dagan's user avatar

Bash has Array Support, We just need to supply values dynamically :)

Bash Array Documentation : http://tldp.org/LDP/abs/html/arrays.html

Hemant Patel's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

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

  • The Overflow Blog
  • Rust is evolving from system-level language to UI and frontend development
  • Featured on Meta
  • Preventing unauthorized automated access to the network
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Proposed designs to update the homepage for logged-in users
  • Feedback Requested: How do you use the tagged questions page?

Hot Network Questions

  • Is it ethical to make money off your own lecture notes, lectures, or technical reports?
  • Configuring XYZ source
  • Why is the foundation of a passive portfolio better than active?
  • Implications of posting copyrighted material on Stack Exchange
  • Can I only render edges during an animation in Blender 4?
  • How does conservation of charge explain Kirchhoff's current law?
  • What does Kant mean by pure intuitions, and why are they not separate from the faculty of sensibility?
  • Conditional Probability: Making the right assumptions
  • Meaning of the joke A: "how much coke do you do" B: "Yes."
  • How much leverage would an advantageous position for trade give in a post-collapse period?
  • Growing food by firelight
  • A novel about an object from space crossing the solar system and found out not to be an asteroid but a spaceship. Not Greg Bear's Eon
  • Are slurs necessary for a piano tremolo, and if so what does their presence indicate?
  • Does this metal plate stay on my prehung door frame after installation?
  • calling python within bash script
  • How do office poster laws affect businesses with no office?
  • Proof of uniqueness of convex sets using their support functions
  • Are there any special actions that I should execute as a reviewer of a sloppy manuscript?
  • Accidentally drilled holes through dryer duct
  • Can weapon special abilities be activated at the same time with a single command?
  • Is there any direct evidence for or against the idea of an alternate ending to Big?
  • Why "geometria" and not "geometrica"?
  • How can someone leave The Island on Lost?
  • Why not send a Mars rover to Titan?

awk command line variable assignment

Previous: Using Variables in a Program , Up: Variables   [ Contents ][ Index ]

6.1.3.2 Assigning Variables on the Command Line ¶

Any awk variable can be set by including a variable assignment among the arguments on the command line when awk is invoked (see Other Command-Line Arguments ). Such an assignment has the following form:

With it, a variable is set either at the beginning of the awk run or in between input files. When the assignment is preceded with the -v option, as in the following:

the variable is set at the very beginning, even before the BEGIN rules execute. The -v option and its assignment must precede all the file name arguments, as well as the program text. (See Command-Line Options for more information about the -v option.) Otherwise, the variable assignment is performed at a time determined by its position among the input file arguments—after the processing of the preceding input file argument. For example:

prints the value of field number n for all input records. Before the first file is read, the command line sets the variable n equal to four. This causes the fourth field to be printed in lines from inventory-shipped . After the first file has finished, but before the second file is started, n is set to two, so that the second field is printed in lines from mail-list :

Command-line arguments are made available for explicit examination by the awk program in the ARGV array (see Using ARGC and ARGV ). awk processes the values of command-line assignments for escape sequences (see Escape Sequences ). (d.c.)

Normally, variables assigned on the command line (with or without the -v option) are treated as strings. When such variables are used as numbers, awk ’s normal automatic conversion of strings to numbers takes place, and everything “just works.”

However, gawk supports variables whose types are “regexp”. You can assign variables of this type using the following syntax:

Strongly typed regexps are an advanced feature (see Strongly Typed Regexp Constants ). We mention them here only for completeness.

  • Getting started with awk
  • Built-in functions
  • Built-in Variables
  • Patterns and Actions
  • Row Manipulation
  • String manipulation functions
  • Two-file processing
  • Useful one-liners - calculating average from a CSV etc
  • Assignment Arguments
  • Command-line variable assignment
  • Local variables
  • Passing parameters to a program using the -v option

awk Variables Command-line variable assignment

Fastest entity framework extensions.

To assign variables from the command-line, -v can be used:

Note that there are no spaces around the equal sign.

This allows to use shell variables:

Also, this allows to set built-in variables that control awk :

See an example with FS (field separator):

Or with OFS (output field separator):

Got any awk Question?

pdf

  • Advertise with us
  • Cookie Policy
  • Privacy Policy

Get monthly updates about new articles, cheatsheets, and tricks.

IMAGES

  1. AWK Command in Linux with Examples {Statements, Patterns & Variables}

    awk command line variable assignment

  2. AWK Command in Linux with Examples

    awk command line variable assignment

  3. AWK Command in Linux with Examples {Statements, Patterns & Variables}

    awk command line variable assignment

  4. Learn How to Use Awk Variables, Numeric Expressions and Assignment

    awk command line variable assignment

  5. Learn How to Use Awk Variables, Numeric Expressions and Assignment

    awk command line variable assignment

  6. AWK Command in Linux with Examples

    awk command line variable assignment

VIDEO

  1. Interactive Simulation of Dynamic Crowd Behaviors using General Adaptation Syndrome Theory

  2. Border outline design:: project outline #project #art #drawing #borderart #shortsfeed #shorts

  3. Machine Learning #2; Types of Algorithms in Machine Learning

  4. 12-របៀបប្រើប្រាស់ និងកំណត់​ Command Dimension ត

  5. Variable quantitative discrète

  6. COMP6980