dudu
dudu

Reputation: 849

shell: how to read a certain column in a certain line into a variable

I want to extract the first column of the last line of a text file. Instead of output the content of interest in another file and read it in again, can I just use some command to read it into a variable directly? For exampole, if my file is like this:

...  
123 456 789(this is the last line)  

What I want is to read 123 into a variable in my shell script. How can I do that?

Upvotes: 0

Views: 3677

Answers (3)

user4401178
user4401178

Reputation:

You could also use sed: $> var=$(sed -nr '$s/(^[^ ]*).*/\1/p' "file.txt")

The -nr tells sed to not output data by default (-n) and use extended regular expressions (-r to avoid needing to escape the paranthesis otherwise you have to write \( \))). The $ is an address that specifies the last line. The regular expression anchors the beginning of the line with the first ^, then matches everything that is not a space [^ ]* and puts that the result into a capture group ( ) and then gets rid of the rest of the line .* by replacing the line with the capture group \1, then print p to print the line.

Upvotes: 0

user1934428
user1934428

Reputation: 22291

I guess with "first column", you mean "first word", do you?

If it is guaranteed, that the last line doesn't start with a space, you can do

tail -n 1 YOUR_FILE | cut -d ' ' -f 1

Upvotes: 0

Charles Duffy
Charles Duffy

Reputation: 295649

One approach is to extract the line you want, read its columns into an array, and emit the array element you want.

For the last line:

#!/bin/bash
#      ^^^^- not /bin/sh, to enable arrays and process substitution

read -r -a columns < <(tail -n 1 "$filename") # put last line's columns into an array
echo "${columns[0]}"                          # emit the first column

Alternately, awk is an appropriate tool for the job:

line=2
column=1
var=$(awk -v line="$line" -v col="$column" 'NR == line { print $col }' <"$filename")
echo "Extracted the value: $var"

That said, if you're looking for a line close to the start of a file, it's often faster (in a runtime-performance sense) and easier to stick to shell builtins. For instance, to take the third column of the second line of a file:

{
  read -r _           # throw away first line
  read -r _ _ value _ # extract third value of second line
} <"$filename"

This works by using _s as placeholders for values you don't want to read.

Upvotes: 1

Related Questions