LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   problem with ' set $(cat crpage)' (https://www.linuxquestions.org/questions/linux-newbie-8/problem-with-set-%24-cat-crpage-877438/)

boumphreyfr 04-27-2011 01:04 PM

problem with ' set $(cat crpage)'
 
I have several lines of text that I want to sort by line and display
Code:


#!/bin/bash
crpage="
                              NEW YORK
                        HENRY HOLT AND COMPANY
                                  1916
                      [several more lines...]
                    J. R., L. E. W., and L. T. S.,
                  without whose help this small record
                      could not have been written."

        IFS=$'\n'
        set $(cat crpage)
        echo $1
        echo $2
        echo $15
exit

The proble is $1 and $2 show the first and second ine but $15 shows:
NEW YORK5
In other words line 1 !!

Ie tried quotes with no success. Any ideas?


David the H. 04-27-2011 01:26 PM

Positional parameters larger than 9 need to use the full variable form: "${15}".

And from now on, please use [code][/code] tags around your code, to preserve formatting and to improve readability.

boumphreyfr 04-27-2011 03:01 PM

Thankyou
My first post didn't know about [code][code] ,should have RTFM
Frank
P.S.
I have now added code tags

David the H. 04-28-2011 07:37 AM

Not to worry. It's common with newcomers.

Although I would've put the ending tag after the last line of code instead of the end of the post. ;)

A couple more things to comment on:

You can usually use redirections instead of cat when accessing file contents. In this case you can use:
Code:

set $( <crpage )
Personally, I don't like using set/shift with the positional parameters. I prefer to use arrays instead. Bash v.4 even has a new mapfile built-in that makes it easy to load lines from a file into an array.
Code:


mapfile -t arr <crpage    #-t removes the trailing newline
   
#or for earlier versions of bash:
#IFS=$'\n'
#arr=( $(<crpage) )

echo "${arr[0]}"          #you should generally quote variable expansions
echo "${arr[1]}"          #especially when they can contain spaces
echo "${arr[14]}"          #and other shell-reserved characters

There's no need to fool with IFS this way either (at least, not with v.4). The only thing you have to remember is that arrays are 0-indexed, so you need to subtract one from each line number to reference it. :)

(Or mapfile also has an -O option, which lets you set the index start number to whatever you want.)


All times are GMT -5. The time now is 02:38 PM.