0

i am using grep command to create an array using data from a file. These is a sample from a file abc.xyz

[abc] Hello world
[abc] qwertyuy
[qwe] poiuyttrr
[abc] Zzxcvzxvxczv

I want to store each of the lines in an array which is having word'[abc]' in the begining I am using the following command

grep -n "\[abc\]" abc.xyz

And storing it in a variable, But the varaiable is got getting stored as an array. Please suggest how to do it.

1 Answer 1

2

Assuming you have Bash or Korn shell:

var=( $(grep -n "\[abc\]" abc.xyz) )

The var=( … ) creates the array. The $( … ) executes a command and the result is tokenized. Note that the tags etc will be split into separate words. For your input file, the output is:

$ printf "%s\n" "${var[@]}"
1:[abc]
Hello
world
2:[abc]
qwertyuy
4:[abc]
Zzxcvzxvxczv
$

If you want to split on newlines, you have to play with IFS:

$ old="$IFS"
$ IFS=$'\n'    # Bash - may not be available in ksh
$ var=( $(grep -n "\[abc\]" abc.xyz) )
$ IFS="$old"
$ print "%s\n" "${var[@]}"
1:[abc] Hello world
2:[abc] qwertyuy
4:[abc] Zzxcvzxvxczv
$
Sign up to request clarification or add additional context in comments.

Comments

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.