-1

I want to extract from a file named datax.txt the second line being :

0/0/0/0/0/0   |   0/0/0/0/0/0   |   0/0/0/0/0/0

And then I want to store in 3 variables the 3 sequences 0/0/0/0/0/0.

How am I supposed to do?

Inian
  • 80,270
  • 14
  • 142
  • 161
imrems
  • 47
  • 3

4 Answers4

3

Read the 2nd line into variables a,b and c.

read a b c <<< $(awk -F'|' 'NR==2{print $1 $2 $3}' datax)
suspectus
  • 16,548
  • 8
  • 49
  • 57
1

the keys is to split the problem in two:

  • you want to get the nth line of a file -> see here
  • you want to split a line in chunks according to a delimiter -> that's the job of many tools, cut is one of them

For future questions, be sure to include a more complete dataset, here is one for now. I changed a bit the second line so that we can verify that we got the right column:

f.txt

4/4/4/4/4/4 | 4/4/4/4/4/4 | 4/4/4/4/4/4
0/0/0/0/a/0 | 0/0/0/0/b/0 | 0/0/0/0/c/0
8/8/8/8/8/8 | 8/8/8/8/8/8 | 8/8/8/8/8/8
8/8/8/8/8/8 | 8/8/8/8/8/8 | 8/8/8/8/8/8

Then a proper script building on the two key actions described above:

extract.bash

file=$1
target_line=2

# get the n-th line
# https://stackoverflow.com/questions/6022384/bash-tool-to-get-nth-line-from-a-file
line=$(cat $file | head -n $target_line | tail -1)

# get the n-th field on a line, using delimiter '|'
var1=$(echo $line | cut --delimiter='|' --fields=1)
echo $var1
var2=$(echo $line | cut --delimiter='|' --fields=2)
echo $var2
var3=$(echo $line | cut --delimiter='|' --fields=3)
echo $var3

aaand:

$ ./extract.bash f.txt
0/0/0/0/a/0
0/0/0/0/b/0
0/0/0/0/c/0
  • the fact is there are more spaces : 0/0/0/0/0/0 | 0/0/0/0/0/0 | 0/0/0/0/0/0 there are 3, how do I bypass them ? otherwise, it works for the first sequence – imrems Sep 05 '19 at 08:26
  • I don't get what you mean by `there are 3` - are you telling that there is a variable number of spaces per line? I would suggest that you upload a snippet of your `datax.txt` file – Grégoire Roussel Sep 05 '19 at 08:57
0

Please try the following:

IFS='|' read a b c < <(sed -n 2P < datax | tr -d ' ')

Then the variables a, b and c are assigned to each field of the 2nd line.

tshiono
  • 21,248
  • 2
  • 14
  • 22
0

You can use sed to print a specific line of a file, so for your example on the second line:

sed -n -e 2p ./datax

Set the output of the sed to be a variable:

Var=$(sed -n -e 2p ./datax)

Then split the string into the 3 variables you need:

 A="$(echo $Var | cut -d'|' -f1)"
 B="$(echo $Var | cut -d'|' -f2)"
 C="$(echo $Var | cut -d'|' -f3)"
Bobybobp
  • 95
  • 9