perlselami perlselami - 1 year ago 81
Bash Question

How can I read/print a specific column using bash script?

My code and input file are below. But my code doesn't print what I want. It prints all contents of the input file. But I want to print only "standard deviation" column. How can I do this using bash script?

My code:

while IFS= read -r line
echo "$line" >> out.xvg
done <"$file"


The terms of the GNU Lesser General Public License
as published by the Free Software Foundation; either version
of the License.

Read 2 sets of 201 points, dt = 0.01

set average deviation

a1 2.445857e+01 2.145235e+01
a2 -1.158344e+02 5.452454e+01
a3 2.314415e+04 3.652432e+05
a4 -5.153647e-03 7.235728e-02

Requested output:



sed '/a1/,$!d' input.xvg | sed '$d' | awk '{print $3}' > output.txt

This code works but it ignores the last line of the file. I checked the input file. That is missing the newline character after its last line. But I want to print all lines of "standard deviation" column. How can I fix this problem?

Answer Source

with the cut argument you can solve your problem :

echo "$line" | tr -s " " | cut -d " " -f 3

tr -s " " remove all the " " (space) char to only one. cut -d define your delimiter and -f chose the colomn your wanna print (fieldset)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download