0

I have a set of data in a text file.

aaa:bbb:ccc
ddd:fff:ggg

, seperated by ':' and I have a variables 1,2 and 3. How to seprate the data like lets say I am intrested in only aaa line. So I will have 1=aaa,2=bbb and 3=ccc.

Tried using

1=grep "$a" textfile.txt | awk -F ':' '{print $1}'

2=grep "$a" textfile.txt | awk -F ':' '{print $2}'

3=grep "$a" textfile.txt | awk -F ':' '{print $3}'

but does not work. Please advice. Thanks!

3 Answers 3

3

try this:

VAR1=$(grep "$a" textfile.txt | awk -F ':' '{print $1}')
VAR2=$(grep "$a" textfile.txt | awk -F ':' '{print $2}')
VAR3=$(grep "$a" textfile.txt | awk -F ':' '{print $3}')

Your variable must not be just numbers and you need to set the output of the grep to the var (not the command itself)

EDIT:

You could also use the following:

VAR1=$(awk -F ':' '{print $1}' textfile.txt)
VAR2=$(awk -F ':' '{print $2}' textfile.txt)
VAR3=$(awk -F ':' '{print $3}' textfile.txt)
Sign up to request clarification or add additional context in comments.

1 Comment

hmm...how to store numbers?
2

The simplest you can get these variables is by using BASH array using read bulletin:

> read -a arr< <(IFS=':' && grep "aaa" file)
> printf "%s\n" "${arr[@]}"
aaa
bbb
ccc

Comments

2

If you want to use the positional parameters, you can use a subshell and the IFS variable to extract the values:

$ line="aaa:bbb:ccc"
$ set -- $(IFS=:; echo $line)
$ echo $1
aaa
$ echo $2
bbb
$ echo $3
ccc

To iterate over the file, using the positional parameters is needlessly opaque:

while IFS=: read -r a b c; do
    echo "$((++line)), a=$a b=$b c=$c"
done < file
1, a=aaa b=bbb c=ccc
2, a=ddd b=fff c=ggg

2 Comments

is it possible to perform arithmetic operations as well?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.