Monday, September 5, 2022

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

Issue

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:

#!/bin/bash
file="/path/input.txt"
while IFS= read -r line
do
   echo "$line" >> out.xvg
done <"$file"

input.txt:

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


                       standard      
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:

2.145235e+01   
5.452454e+01  
3.652432e+05  
7.235728e-02 

Updated:

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?


Solution

With the cut argument you can solve your problem :

echo "$line" | tr -s " " | cut -d " " -f 3
  • tr -s " " removes all the " " (spaces) char to only one.
  • cut -d defines your delimiter
  • -f choses the colomn your want to print out (fieldset)


Answered By - Will
Answer Checked By - Marilyn (WPSolving Volunteer)