The Cookie Machine - Click here to drag window

DUMMY TEXT - Real text set in assets/js/theCookieMachine.js

Views: 4,191β€…    Votes:  2β€…
Tags: bash   sed   awk   cut-command   tr  
Link: πŸ” See Original Answer on Ask Ubuntu πŸ”—

Title: How would you separate fields with multiple spaces and store them in an array?
ID: /2019/12/08/How-would-you-separate-fields-with-multiple-spaces-and-store-them-in-an-array_
Created: December 8, 2019    Edited:  December 9, 2019
Upload: November 24, 2022    Layout:  post
TOC: false    Navigation:  false    Copy to clipboard:  false

This answer focuses on removing two heading lines from the array to match output requirements.

$ cat fieldone.txt
field1                    field2
------                    -------
this are numbers          12345
this letters              abc def ghi 

$ fieldone
this are numbers         
this letters             

Here is the script:


# NAME: fieldone
# PATH: $HOME/askubuntu/
# DESC: Answer for:
# how-would-you-separate-fields-with-multiple-spaces-and-store-them-in-an-array

# DATE: December 8, 2019.

i=0                                     # Current 0-based array index number
while read line; do                     # Read all lines from input file
    ((LineNo++))                        # Current line number of input file
    [[ $LineNo -eq 1 ]] && continue     # "Field 1     Field 2" skip first line
    if [[ $LineNo -eq 2 ]] ; then       # Is this is line 2?
        # Grab the second column position explained in:
        # how-to-find-a-position-of-a-character-using-grep
        Len="$(grep -aob ' -' <<< "$line" | \grep -oE '[0-9]+')"
        continue                        # Loop back for first field

    field_one[$i]="${line:0:$Len}"      # Extract line position 0 for Len
    echo "${field_one[i]}"              # Display array index just added
    ((i++))                             # Increment for next array element

done < fieldone.txt                     # Input filename fed into read loop

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:

field1         field2
------         ------
this is letter abcdef
this is number 123456
⇧ How to remove /dev/loops Setting monitor scaling to 200% with xrandr  β‡©