在文件中查找文本值,将其打印出来?

时间:2011-09-01 18:16:52

标签: shell

我有一个shell脚本。我想打开一个文件,并从文件中复制出一些文字。例如:

// foo.java

public static int ID_RED = 100;
public static int ID_GREEN = 200;
public static int ID_BLUE = 300;

//伪代码:

int pos = find("public static int ID_RED = ");
echo(file.substring(pos, end of line);

pos = find("public static int ID_GREEN = ");
echo(file.substring(pos, end of line);

pos = find("public static int ID_BLUE = ");
echo(file.substring(pos, end of line);

//所需的输出:

100
200
300

所以我想打开foo.java,并打印出这些行末尾的值。我认为在perl或python中执行此操作会更容易,但是想看看是否有一种简单的方法可以在shell脚本中执行此操作,

3 个答案:

答案 0 :(得分:1)

sed -n '/^public static int ID_/{s/;.*$//;s/.* //p;}' foo.java

如果可能存在前导空格,请考虑将^public替换为^ *public。如果您不想匹配ID_,请将ID_\(RED\|GREEN\|BLUE\)\>替换为ID_YELLOW

答案 1 :(得分:0)

这可以帮助您入门:

#!/bin/bash
grep "public static int ID_RED = "   foo.java | cut -d " " -f 6 | tr -d \;
grep "public static int ID_GREEN = " foo.java | cut -d " " -f 6 | tr -d \;
grep "public static int ID_BLUE = "  foo.java | cut -d " " -f 6 | tr -d \;

答案 2 :(得分:0)

awk -F '[ ;]' '/public static int/ {print $(NF-1)}' foo.java

sed -n '/public static int/ {s/^.*= *\([0-9]\+\);/\1/; p}' foo.java