使用 bash 脚本解析文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10859491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing text with bash script
提问by Dimitris
I want to build a bash script that reads a file and produces some command line parameters. my input file looks like
我想构建一个读取文件并生成一些命令行参数的 bash 脚本。我的输入文件看起来像
20.83 0.05 0.05 __adddf3
20.83 0.10 0.05 __aeabi_fadd
16.67 0.14 0.04 gaussian_smooth
8.33 0.16 0.02 __aeabi_ddiv
I must detect and copy all the __* strings and turncate them into a command such as
我必须检测并复制所有 __* 字符串并将它们转换为命令,例如
gprof -E __adddf3 -E __aeabi_fadd -E __aeabi_ddiv ./nameof.out
So far I use
到目前为止我使用
#!/bin/bash
while read line
do
if [[ "$line" == *__* ]]
then
echo $line;
fi
done <input.txt
to detect the requested lines but i guess, what i need is a one-line-command thing that i can't figure out. Any kind suggestions?
检测请求的行,但我想,我需要的是一个我无法弄清楚的单行命令。有什么好的建议吗?
回答by Paused until further notice.
Modifying your script:
修改你的脚本:
#!/bin/bash
while read -r _ _ _ arg
do
if [[ $arg == __* ]]
then
args+=("-E" "$arg")
fi
done <input.txt
gprof "${args[@]}" ./nameof.out
The underscores are valid variable names and serve to discard the fields you don't need.
下划线是有效的变量名,用于丢弃不需要的字段。
The final line executes the command with the arguments.
最后一行执行带有参数的命令。
You can feed the result of another command into the whileloop by using process substitution:
您可以while使用进程替换将另一个命令的结果输入到循环中:
#!/bin/bash
while read -r _ _ _ arg
do
if [[ $arg == __* ]]
then
args+=("-E" "$arg")
fi
done < <(gprof some arguments filename)
gprof "${args[@]}" ./nameof.out
回答by ghoti
One more way to skin the cat:
另一种给猫剥皮的方法:
gprof `sed -ne '/__/s/.* / -E /p' input.txt` ./nameof.out
The sed script searches for lines with __, then changes everything up to the last space with -Eand prints the result. You may have to adjust things a little if your whitespace could include tabs. For clarity, I didn't account for that here.
sed 脚本搜索带有 的行__,然后将所有内容更改为直到最后一个空格-E并打印结果。如果您的空格可能包含制表符,您可能需要稍微调整一下。为清楚起见,我没有在这里说明。
回答by Prince John Wesley
Using awk:
使用awk:
awk ' ~/^__/{a=a" -E "}END{system("gprof "a" ./nameof.out")}' inputFile

