Taking this path to a file: words/05_díj/díj_pct.txt how I can extract only this part? 05

What I want is to use that part as a value for an external variable for the execution of an awk script.


for f in words/*/*_pct.txt
  #So, I want to extract "05" from $f

  #To use it here
awk -v var -f script.awk "$f" >> words/results.txt
  • Is there a specific pattern to the directory 05_dij? Are you simply after the first two characters, or could that sometimes be (e.g.) 1234_xyz and you need the 1234? Please edit your question to be more specific. – garethTheRed Mar 7 '16 at 8:47
  • The subdirectory name will always be 05_whatever 06_whatever 08_whatever . Only two digits. – Firefly Mar 7 '16 at 8:54

Using parameter expansion:

for f in words/*/*_pct.txt; do
  n=${f#*/}   # Remove everything till the first slash
  n=${n%%_*}  # Remove everything from the first underscore to the end
  awk -v var="$n" -f script.awk "$f" >> words/results.txt

Note you need to quote -v var="$n", and if $n contain escaped sequences, they will be expanded.

| improve this answer | |
  • But I want the argument of the awk script remains the full path. What I need is to store "05" in a variable. I don't want to alter the value of $f – Firefly Mar 7 '16 at 9:02
  • I'm Trying this, to try. var="words/05_díj/díj_pct.txt"; n=${var#*/}; n=${var%%_*}; echo $n and the result is words/05 not only "05" – Firefly Mar 7 '16 at 9:22
  • @Firefly: Sorry, it's var="words/05_díj/díj_pct.txt"; n=${var#*/}; n=${n%%_*}; echo "$n" – cuonglm Mar 7 '16 at 9:30

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.