2

I have a file from which I extract the first three columns using the cut command and write them into an array.

When I check the length of the array , it is giving me four. I need the array to have only 3 elements.

I think it's taking space as the delimiter for array elements.

aaa|111|ADAM|1222|aauu

aaa|222|MIKE ALLEN|5678|gggg
aaa|333|JOE|1222|eeeee

target=($(cut -d '|' -f1-3 sample_file2.txt| sort -u ))
2
  • You need the first three fields of each line as single array elements? See mywiki.wooledge.org/BashFAQ/001 Commented Jun 16, 2015 at 19:01
  • yes, i need the first three fields as a single element in an array Commented Jun 16, 2015 at 19:15

3 Answers 3

2

In bash 4 or later, use readarray with process substitution to populate the array. As is, your code cannot distinguish between the whitespace separating each line in the output from the whitespace occurring in "Mike Allen". The readarray command puts each line of the input into a separate array element.

readarray -t target < <(cut -d '|' -f1-3 sample_file2.txt| sort -u)

Prior to bash 4, you need a loop to read each line individually to assign to the array.

while IFS='' read -r line; do
    target+=("$line")
done < <(cut -d '|' -f1-3 sample_file2.txt | sort -u)
Sign up to request clarification or add additional context in comments.

3 Comments

Hi, can we use readarray in bash? I have got the error when i tried the above command
You do need to be using bash 4 or later. Otherwise, you need to use something a little messier.
I had a typo in my description. The loop version should work for any thing in the 3.x series.
1

This should work:

IFS=$'\n' target=($(cut -d '|' -f1-3 sample_file2.txt| sort -u ))

Example:

#!/bin/bash
IFS=$'\n' target=($(cut -d '|' -f1-3 sample_file2.txt| sort -u ))
echo ${#target[@]}
echo "${target[1]}"

Output:

3
aaa|222|MIKE ALLEN

Comments

0

As an alternative, using the infamous eval,

eval target=($(cut -sd '|' -f1-3 sample_file2.txt | sort -u | \
               xargs  -d\\n printf "'%s'\n"))

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.