I would like to create a bash script that selects the first word of each line from a text file before the ":" character, and outputs it in an array (1 slot for 1 line).

Right now I have this:

while read p; 
  arr+=$p | sed -r 's///'
done <test.txt

and I can't figure out what to put in the condition of the sed.

I have this regexep :


No need for a subshell and sed, just use parameter expansion:

while read p ; do
  arr+=( "${p%%:*}" )
done < test.txt

It might be faster to remove all the substrings in one command

while read p ; do
done < test.txt
  • thanks a lot for this responce, I have another question : I would like to use every element from the array "arr" and use them in a sed to repalce them if found in a text file has such : for i in "${arr[@]" fo sed -r 's/$i/USERNAME/g' /../var/log/auth.log > /../root/sword-anon-connections.log done but I think there is a problem with the variable – ndfg201 May 1 '18 at 22:35
  • To ask a new question, create a new question. Also, variables aren't expanded in single quotes. – choroba May 1 '18 at 22:38
  • In bash 4.0+, the loop could be simplified to: <infile readarray -t arr – Isaac May 1 '18 at 22:45

With bash 4 or later, you may use readarray to read directly into an array:

readarray -t arr < <( awk -F ':' '{ print $1 }' file.in )

The awk code runs in a process substitution and provides the data. It simply extracts the first field of each :-delimited line.

Example with file.in as

roses are:red
violets:are blue
sugar is:sweet and
$ readarray -t arr < <( awk -F ':' '{ print $1 }' file.in )
$ printf '"%s"\n' "${arr[@]}"
"roses are"
"sugar is"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.