In my file mytxt
:
field1 field2
------ -------
this are numbers 12345
this letters abc def ghi
Let's say I want to store the first field in an array:
i=0
while read line; do
field_one[$i]=$(echo $line | awk '{print $1}')
echo ${field_one[i]}
((i++))
done < mytxt
That would give me the this
two times in the output.
Any ideas of how could I store them in an array and get the output:
this are numbers
this letters
I have tried changing delimiters, squeezing spaces, and using sed
, but I'm stuck. Any hint would be appreciated.
My final goal is to store both fields in an array.
Using colrm to remove columns from file.
(Bash builtin version):
You could use the bash builtin
mapfile
(akareadarray
) with a callback that uses parameter expansion to trim the longest trailing substring starting with two spaces:Ex. given
then
This answer focuses on removing two heading lines from the array to match output requirements.
Here is the script:
Hopefully code and comments are self explanatory. If not don't hesitate to comment.
The script still works if only one space separates the two columns whereas some other answers will break:
Moving my comment, based on this source, to just show a particular column on multiple-spaces based table:
Note that this won't work if you use double quotes.
I found it particularly useful to find duplicates, using something like: