简体   繁体   English

Bash Shell脚本为grep搜索的输出分配新变量

[英]Bash Shell Scripting assigning new variables for output of a grep search

EDIT 2: I've decided to re-write this in order to better portray my outcome. 编辑2:为了更好地描述我的结果,我决定重写此内容。

I'm currently using this code to output a list of files within various directories: 我目前正在使用此代码输出各个目录中的文件列表:

for file in /directoryX/*.txt

do
     grep -rl "Annual Compensation" $file
done

The output shows all files that have a certain table I'm trying to extract in a layout like this: 输出显示的是所有具有特定表的文件,而这些表我正尝试以这种布局提取:

txtfile1.txt
txtfile2.txt
txtfile3.txt

I have been using this awk command on each individual .txt file to extract the table and then send it to a .csv: 我一直在每个单独的.txt文件上使用此awk命令来提取表,然后将其发送到.csv:

awk '/Annual Compensation/{f=1} f{print; if (/<\/TABLE>/) exit}' txtfile1.txt > txtfile1.csv

My goal is to find a command that will run my awk command against each file in the list all at once. 我的目标是找到一个命令,一次对列表中的每个文件运行我的awk命令。 Thank you to those that have provided suggestions already. 谢谢那些已经提供建议的人。

If I understand what you're asking, I think what you want to do is add a line after the grep, or instead of the grep, that says: 如果我了解您的要求,我想您想做的就是在grep后面添加一行,或者代替grep来写:

awk '/Annual Compensation/{f=1} f{print; if (/<\/TABLE>/) exit}' $file > ${file}_new.csv

When you say ${file}_new.csv , it expands the file variable, then adds the string "_new.csv" to it. 当您说${file}_new.csv ,它将扩展file变量,然后向其添加字符串“ _new.csv”。 That's what you're shooting for, right? 那就是你的目标,对吧?

Modifying your code: 修改代码:

for file in /directoryX/*.txt
do
    files+=($(grep -rl "Annual Compensation" $file))
done

for f in "${files[@]}";do
    awk '/Annual Compensation/{f=1} f{print; if (/<\/TABLE>/) exit}' "$f" > "$f"_new.csv
done

Alternative code: 备用代码:

files+=($(grep -rl "Annual Compensation" /directoryX/*))
for f in "${files[@]}";do
awk '/Annual Compensation/{f=1} f{print; if (/<\/TABLE>/) exit}' "$f" > "$f"_new.csv

In both cases, the grep results and awk results are not verified by me - it is just a copy - paste of your code. 在这两种情况下,我都无法验证grep结果和awk结果-这只是一个副本-您的代码粘贴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM