问题
when I do this:
LINE=$(head -38 fine.txt | tail -1 | cut -f2)
I get the 38th line of the file, which is:
Xres = 1098
but I only need to record 1098 as value for a variable.
I am training to read a text file and record values and use them as parameters later in my script.
回答1:
Add | awk '{print $3}' to the pipeline.
回答2:
sed -n '38s/.*= *//p' fine.txt
By default, sed prints every input line. The -n option disables this behavior. 38 selects line number 38 and when this line is seen, the substitution replaces everything up to the last equals sign with nothing, and prints.
That's assuming the second field is the last field. If the input line is more complex than I have assumed, try the substitution s/^[^\t]*\t[^\t]*= *//p. If your sed does not recognize \t as a tab character, you'll need to supply literal tabs (you can enter one with the key sequence ctrl-v tab in some shells).
If the input file is large, you may want to refactor the sed script to quit after the 38th line.
Wrapping up, that gets us
LINE=$(sed -n '38!b;s/^[^\t]*\t[^\t]*= *//p;q' fine.txt)
However, this is becoming somewhat complex, to the point of hampering legibility and thus maintainability. The same in Awk is more readable;
awk -F '\t' 'NR==38 { sub(/.*= */,"",$2); print $2; exit 0 }' fine.txt
More generally, you might want to split on tabs, then on spaces. The following implements cut -f2 | awk '{ print $3 }' more precisely:
awk -F '\t' 'NR==38 { split($2,f); print f[3]; exit 0 }' fine.txt
The option -F '\t' sets tab as the input field separator. The condition NR==38 selects the 38th line, and split($2,f) splits the second tab-separated field on spaces into the array f. Then we simply print the third element of f, and exit.
来源:https://stackoverflow.com/questions/21029763/who-to-get-copy-a-specific-word-from-a-text-file-using-bash