2

I have a file named input_file which contains some lines. I need to remove certain characters in the line and store them in an array. So to remove the characters, I use the sed command and storing in a variable as below.

 all_values=$(sed 's/^[^.]*\. //' < input_file) echo "$all_values" 

It is working perfectly fine but I need all_values to be an array so that all_values[0] will contain the first line and all_values[1] the second line and so on.

Since I have a file, I do not know the total array elements before hand. How can I construct an array for my case?

EDIT:

My input file is like below.

This is first element This is second element Though spaces, I should be one element 

    1 Answer 1

    4

    You just need a bit more syntax to store the output in an array

    all_values=( $(sed 's/^[^.]*\. //' < input_file) ) 

    There will be trouble if any of the lines of output contain whitespace: each whitespace separated word will be a separate array element. Please show some sample input if that's the case.


    all_values=() while read -r line; do all_values+=( "$line" ) done < <( sed 's/^[^.]*\. //' input_file ) 

    Or, more tersely

    mapfile -t all_values < <( sed 's/^[^.]*\. //' input_file ) 

    mapfile is a bash built-in: see help mapfile from a bash prompt.


    You don't even need sed for this. If I read your intention is to remove the first sentence from each line:

    $ cat input_file Ignore me. keep me Don't want this. Do want this $ mapfile -t a < input_file $ shopt -s extglob $ a=( "${a[@]#*([^.]). }" ) $ printf "%s\n" "${a[@]}" keep me Do want this 
    2
    • Thanks. Yeah, I do have whitespaces. I will update the question with the sample input.
      – Ramesh
      CommentedFeb 10, 2014 at 18:37
    • I have added the sample input to the question.
      – Ramesh
      CommentedFeb 10, 2014 at 18:39

    You must log in to answer this question.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.