Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a Shell variable in AWK

Tags:

bash

shell

unix

awk

I have strings like this

/home/rm/home-scripts/originals/audicerttest/incoming/TEST040511.txt
/home/rm/home-scripts/originals/audicerttest2/incoming/TEST040512.txt
/home/rm/home-scripts/originals/audicerttest3/incoming/TEST040513.txt

etc..I want to extract strings 'audicerttest/incoming', audicerttest2/incoming' etc into a shell variable and use it later in the script. I tried something like this.

for file in `find ${ROOT}/* -type f | grep -v -f test.txt`
do
let count++
echo ${count}: ${file}
echo ${file} | eval $(awk '{split($0,a,"/"); print "abc=a[6]/a[7]"}' < /dev/null)
echo abc====$abc
done

but its not giving any output for abc.

like image 610
Ravi Avatar asked Apr 11 '26 04:04

Ravi


1 Answers

There are a number of issues, but let's isolate problems and tackle them one at a time.

Given - Raw string:

/home/rm/home-scripts/originals/audicerttest/incoming/TEST040511.txt

Desired Output - You want this part to be saved in a variable:

audicerttest/incoming

How-To - This will do it:

string="/home/rm/home-scripts/originals/audicerttest/incoming/TEST040511.txt"
parsed=$(awk 'BEGIN{FS=OFS="/"} {print $6, $7}' <<< ${string})

In general, suppose you have a file called input_file.txt:

/home/rm/home-scripts/originals/audicerttest/incoming/TEST040511.txt
/home/rm/home-scripts/originals/audicerttest2/incoming/TEST040512.txt
/home/rm/home-scripts/originals/audicerttest3/incoming/TEST040513.txt

You can do:

awk 'BEGIN{FS=OFS="/"} {print $6, $7}' input_file.txt > parsed_vars.txt

And parsed_vars.txt will contain:

audicerttest/incoming
audicerttest2/incoming
audicerttest3/incoming

Some explanations:

  • parsed=$(...) - spawn a subshell and save the output to stdout within that subshell to the variable parsed
  • awk 'BEGIN{FS=OFS="/"} - invoke awk and set delimiter as / for both input and output.
  • {print $6, $7}' - based on the format of your raw strings, you want to print the 6th (audicerttest) and the 7th (incoming) fields.
  • <<< ${string} is the notation for using herestring
  • input_file.txt > parsed_vars.txt - read from specified input file, and redirect output to an output file.
like image 194
sampson-chen Avatar answered Apr 13 '26 14:04

sampson-chen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!