Reputation: 3161
here is the file content:
CPU revision : 0
Hardware : nomen TOS 9900 (Flattened Device Tree)
Revision : nomen TOS 8800 (Flattened Device Tree)
Serial : 0000
using Linux shell script, I need to read this file and get only 9900 (from Hardware: line) into a string, what is the best way? thanks!
Upvotes: 1
Views: 7092
Reputation: 46846
Given the extent of the information you've provided, this is a really easy task using a variety of tools.
$ awk '$1=="Hardware"{print $5}' sample.txt
Awk looks for a match on an expression, then separates the line into fields delimited by whitespace. $1
is the first word, $5
is the fifth "word".
$ sed -ne '/^Hardware/s/[^0-9]//gp' sample.txt
The sed command can also execute commands on lines that match specific regexes. In this case, for "Hardware" lines, we're replacing every non-numeric character with null, which obviously leaves the number. This separates by type rather than by field. (You didn't state what you were trying to achieve.)
And finally:
$ readarray -t stuff < sample.txt
$ for line in "${stuff[@]}"; do this=($line); test "${this[0]}" = "Hardware" && echo "${this[4]}"; done
Without using any external tools, this finds the line using bash alone. Note that this kind of array reference doesn't work in older Bourne-style shells. But if you're in Linux or OSX, your shell is likely bash by default.
And if you're wondering about "${this[4]}"
, the "4" is because bash arrays are numbered from zero, whereas awk lines are word-split starting at $1
.
We could do this in non-bash shell as well, but it would be a lot more work, and probably not a one-liner.
Upvotes: 1