开发者

Find text value in file, print it out?

I've got a shell script. I want to open a file, and copy out a bit of text from the file. Example:

// foo.java

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

// pseudo-code:

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.subs开发者_运维问答tring(pos, end of line);

// desired output:

100
200
300

So I want to open foo.java, and print out the values found at the end of those lines. I think it'd be easier to do this in perl or python, wanted to see if there was a simple way to do this in a shell script, though,


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

This doesn't exactly match the criteria implied by your pseudo-code, but it does the job for this particular input. Consider replacing ^public by ^ *public if there might be leading whitespace. Replace ID_ by ID_\(RED\|GREEN\|BLUE\)\> if you don't want to match ID_YELLOW, for example.


This should help you get started:

#!/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 \;


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

or

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜