在分配AWK shell变量 [英] Assign a Shell variable in AWK

查看:99
本文介绍了在分配AWK shell变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的字符串

/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要提取字符串audicerttest /来电,audicerttest2 /入等成一个shell变量,后来在脚本中使用它。我想这样的事情。

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.

推荐答案

有一些问题,但让我们找出问题并解决他们一次。

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})


在一般情况下,假设你有一个名为 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

您可以这样做:

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

parsed_vars.txt 将包含:

audicerttest/incoming
audicerttest2/incoming
audicerttest3/incoming


的几点说明:


  • 解析= $(...) - 生成一个子shell和子shell内输出保存到标准输出到变量解析

  • 的awk'BEGIN {FS = OFS =/} - 调用 AWK ,并设置分隔符为 / 的输入和输出。

  • {打印$ 6,$ 7} - 根据您的原始字符串格式,要打印第6(audicerttest)和7号(进入)领域。

  • &LT;&LT;&LT; $ {字符串} 是使用符号 herestring

  • input_file.txt&GT; parsed_vars.txt - 从指定的输入文件中读取,并输出重定向到一个输出文件

  • 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.

这篇关于在分配AWK shell变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆