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 $1
to wc.
awk '{system("wc $1")}' myfile
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.
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.
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.
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.
you are close. you have to concatenate the command line with awk variables:
awk '{system("wc "$1)}' myfile
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With