Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass variables from awk to a shell command?

I am trying to run a shell command from within awk for each line of a file, and the shell command needs one input argument. I tried to use system(), but it didn't recognize the input argument.

Each line of this file is an address of a file, and I want to run a command to process that file. So, for a simple example I want to use 'wc' command for each line and pass $1to wc.

awk '{system("wc $1")}' myfile 
like image 240
Vahid Mirjalili Avatar asked Dec 17 '13 23:12

Vahid Mirjalili


People also ask

How do I export a variable from awk?

On your machine, try this command: ll -d /dev/{std*,fd} . In my solution, I need to send the line-by-line output one place and the END print output another, so awk's stdout is redirected to a file, and stderr is redirected to stdout so the variable can grab it.

Can we use awk in shell script?

Awk is an excellent tool for building UNIX/Linux shell scripts. AWK is a programming language that is designed for processing text-based data, either in files or data streams, or using shell pipes. In other words you can combine awk with shell scripts or directly use at a shell prompt.

How do you pass a variable to a variable in shell script?

In a shell script, you can pass variables as arguments by entering arguments after the script name, for example ./script.sh arg1 arg2 . The shell automatically assigns each argument name to a variable. Arguments are set of characters between spaces added after the script.

How do you pass command line arguments in awk?

Arguments given at the end of the command line to awk are generally taken as filenames that the awk script will read from. To set a variable on the command line, use -v variable=value , e.g. This would enable you to use num as a variable in your script. The initial value of the variable will be 10 in the above example.


1 Answers

you are close. you have to concatenate the command line with awk variables:

awk '{system("wc "$1)}' myfile 
like image 145
Kent Avatar answered Oct 22 '22 13:10

Kent