LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   bash script stdin accept values separated with new lines, commas, spaces (http://www.linuxquestions.org/questions/programming-9/bash-script-stdin-accept-values-separated-with-new-lines-commas-spaces-778652/)

m4rtin 12-29-2009 05:48 AM

bash script stdin accept values separated with new lines, commas, spaces
 
I have a script, where STDIN(numbers from a text file) is copied from a text file using mouse and pasted to the terminal window.

Code:

user@computer:~>./script -o -t <PASTE NUMBERS GOES HERE>
I mean the user should type ./script -o -t , then open this text file and copy particular numbers and paste those into the terminal window right after the ./script -o -t . The point is, that those numbers may be separated with space, with commas or with new lines:
Quote:

TEXT FILE EXAMPLE1:
----------
85 72 33423 2389 2312310
----------

TEXT FILE EXAMPLE2:
----------
23748923, 234723, 2, 0923, 1
----------

TEXT FILE EXAMPLE3:
----------
324
4
5
1231
18
----------
Is it possible to have a script, which is able to take input weather it's separated using commas, new lines or spaces?

ghostdog74 12-29-2009 07:23 AM

tell your user to put quotes when they key in the argument
Code:

./script -t -o "paste here"
or inside your script, save $@ to variable

m4rtin 12-29-2009 07:36 AM

Quote:

Originally Posted by ghostdog74 (Post 3807732)
tell your user to put quotes when they key in the argument
Code:

./script -t -o "paste here"
or inside your script, save $@ to variable

could you explain this $@ variable option?

ghostdog74 12-29-2009 08:31 AM

$@ contains all your arguments. Read the bash manual.

ta0kira 12-30-2009 06:19 AM

Quote:

Originally Posted by ghostdog74 (Post 3807777)
$@ contains all your arguments. Read the bash manual.

Your suggestion to quote was a better one. This will fail if a double-space has similar meaning to ,, (i.e. an empty field.) My suggestion is to use standard input and not have to worry about all of this.
Kevin Barry

ta0kira 12-30-2009 06:26 AM

Now that I mention it, your question is rather ambiguous. Does the user press [Enter] before pasting? It doesn't look like it, but what you've described isn't standard input; it's command-line arguments. Can you post a basic example? Of a script, input, and what's expected to happen.

Regarding the question you seem to be asking, I'd pipe the input through tr -s ', ' '\n' to put each group on its own line.
Kevin Barry

konsolebox 12-30-2009 07:22 AM

You can make a script accept an argument and split its contents using arrays and the read builtin.

For example:
Code:

#!/bin/bash

IFS=$' ,\t\n'

{
    set -- $1
    NUMBERS=("$@")
}

# or

{
    while read -a TEMP; do
        NUMBERS=("${NUMBERS[@}}" "${TEMP[@]}")
    done
} <<< "$1"

# ---

<do something with NUMBERS[@]>



All times are GMT -5. The time now is 10:31 PM.