Iterate lines of string variable in bashBash : compare two strings with spaceiterate lines containing zeros...

How come Arya Stark didn't burn in Game of Thrones Season 8 Episode 5

Why did the soldiers of the North disobey Jon?

Do high-wing aircraft represent more difficult engineering challenges than low-wing aircraft?

Is there a method to separate iron from mercury?

Is Precocious Apprentice enough for Mystic Theurge?

Resistor Selection to retain same brightness in LED PWM circuit

What kind of action are dodge and disengage?

Can a person still be an Orthodox Jew and believe that the Torah contains narratives that are not scientifically correct?

Would a "ring language" be possible?

What would a Dragon have to exhale to cause rain?

Is there an academic word that means "to split hairs over"?

Promotion comes with unexpected 24/7/365 on-call

multiline equation inside a matrix that is a part of multiline equation

How to know the path of a particular software?

FIFO data structure in pure C

Why use a retrograde orbit?

When did Britain learn about American independence?

Was the dragon prowess intentionally downplayed in S08E04?

​Cuban​ ​Primes

Why are lawsuits between the President and Congress not automatically sent to the Supreme Court

"Counterexample" for the Inverse function theorem

Have there been any examples of re-usable rockets in the past?

Why would you put your input amplifier in front of your filtering for and ECG signal?

Write electromagnetic field tensor in terms of four-vector potential



Iterate lines of string variable in bash


Bash : compare two strings with spaceiterate lines containing zeros in bashUSB ports do not wake up from suspend to RAMnew lines and bash variableBash - assign array into variable as stringFor a large directory, create a variable of the filenames which include lines which include the text string stored in another variablesed - calling a variable from a file with multilineIssues with using multiple * in the grep commandHow to download a web page content to a text file exactly as the web page is?Why can't I use read -a to break a string into words?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







2















I have a script where I want to list USB devices using the command lsblk.



The command:



$ lsblk -o NAME,TRAN,VENDOR,MODEL | grep usb


which results in



sdb   usb    Kingston DataTraveler 2.0
sdc usb Kingston DT 101 G2


I want to save the result in a variable to work later, so I write



$ usbs=$(lsblk -o NAME,TRAN,VENDOR,MODEL | grep usb)


What I was expecting is that the variable usbs stores the result in two whole lines like above. But if I run:



for i in ${usbs[@]}; do
echo $i
done


I get the result split into words:



sdb
usb
Kingston
DataTraveler
2.0
sdc
usb
Kingston
DT
101
G2


Question:
Is there a way in which, using the grep command, I can store the result of the command as two whole lines?



I prefer to know if there's a simple solution instead of dumping the result in a file and then read it.










share|improve this question









New contributor



guillermo chamorro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 1





    Try echo "${#usbs[@]}" to see the number of items in the usbs "array", or "${!usbs[@]}" to list its indices. Or print it with echo "$usbs". It is likely storing what you are expecting it to.

    – fra-san
    5 hours ago








  • 1





    Double-quote your variables (and $(...) constructs) when you reference them and the shell will keep your whitespace intact. But be aware the shell won't automatically assign array elements based on newlines. It will still be one string, just with a newline in the middle.

    – roaima
    5 hours ago













  • @Christopher I like your solution but gave me a headache :), because subsecuents comands use the IFS set before... it took me some time to figure what was happening, it does it silently.

    – guillermo chamorro
    3 hours ago











  • var=$(...) is equivalent to var="$(...)"

    – Jesse_b
    2 hours ago


















2















I have a script where I want to list USB devices using the command lsblk.



The command:



$ lsblk -o NAME,TRAN,VENDOR,MODEL | grep usb


which results in



sdb   usb    Kingston DataTraveler 2.0
sdc usb Kingston DT 101 G2


I want to save the result in a variable to work later, so I write



$ usbs=$(lsblk -o NAME,TRAN,VENDOR,MODEL | grep usb)


What I was expecting is that the variable usbs stores the result in two whole lines like above. But if I run:



for i in ${usbs[@]}; do
echo $i
done


I get the result split into words:



sdb
usb
Kingston
DataTraveler
2.0
sdc
usb
Kingston
DT
101
G2


Question:
Is there a way in which, using the grep command, I can store the result of the command as two whole lines?



I prefer to know if there's a simple solution instead of dumping the result in a file and then read it.










share|improve this question









New contributor



guillermo chamorro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 1





    Try echo "${#usbs[@]}" to see the number of items in the usbs "array", or "${!usbs[@]}" to list its indices. Or print it with echo "$usbs". It is likely storing what you are expecting it to.

    – fra-san
    5 hours ago








  • 1





    Double-quote your variables (and $(...) constructs) when you reference them and the shell will keep your whitespace intact. But be aware the shell won't automatically assign array elements based on newlines. It will still be one string, just with a newline in the middle.

    – roaima
    5 hours ago













  • @Christopher I like your solution but gave me a headache :), because subsecuents comands use the IFS set before... it took me some time to figure what was happening, it does it silently.

    – guillermo chamorro
    3 hours ago











  • var=$(...) is equivalent to var="$(...)"

    – Jesse_b
    2 hours ago














2












2








2








I have a script where I want to list USB devices using the command lsblk.



The command:



$ lsblk -o NAME,TRAN,VENDOR,MODEL | grep usb


which results in



sdb   usb    Kingston DataTraveler 2.0
sdc usb Kingston DT 101 G2


I want to save the result in a variable to work later, so I write



$ usbs=$(lsblk -o NAME,TRAN,VENDOR,MODEL | grep usb)


What I was expecting is that the variable usbs stores the result in two whole lines like above. But if I run:



for i in ${usbs[@]}; do
echo $i
done


I get the result split into words:



sdb
usb
Kingston
DataTraveler
2.0
sdc
usb
Kingston
DT
101
G2


Question:
Is there a way in which, using the grep command, I can store the result of the command as two whole lines?



I prefer to know if there's a simple solution instead of dumping the result in a file and then read it.










share|improve this question









New contributor



guillermo chamorro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











I have a script where I want to list USB devices using the command lsblk.



The command:



$ lsblk -o NAME,TRAN,VENDOR,MODEL | grep usb


which results in



sdb   usb    Kingston DataTraveler 2.0
sdc usb Kingston DT 101 G2


I want to save the result in a variable to work later, so I write



$ usbs=$(lsblk -o NAME,TRAN,VENDOR,MODEL | grep usb)


What I was expecting is that the variable usbs stores the result in two whole lines like above. But if I run:



for i in ${usbs[@]}; do
echo $i
done


I get the result split into words:



sdb
usb
Kingston
DataTraveler
2.0
sdc
usb
Kingston
DT
101
G2


Question:
Is there a way in which, using the grep command, I can store the result of the command as two whole lines?



I prefer to know if there's a simple solution instead of dumping the result in a file and then read it.







bash grep usb variable lsblk






share|improve this question









New contributor



guillermo chamorro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.










share|improve this question









New contributor



guillermo chamorro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








share|improve this question




share|improve this question








edited 26 mins ago









Jeff Schaller

45.8k1165149




45.8k1165149






New contributor



guillermo chamorro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








asked 5 hours ago









guillermo chamorroguillermo chamorro

1143




1143




New contributor



guillermo chamorro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




New contributor




guillermo chamorro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.










  • 1





    Try echo "${#usbs[@]}" to see the number of items in the usbs "array", or "${!usbs[@]}" to list its indices. Or print it with echo "$usbs". It is likely storing what you are expecting it to.

    – fra-san
    5 hours ago








  • 1





    Double-quote your variables (and $(...) constructs) when you reference them and the shell will keep your whitespace intact. But be aware the shell won't automatically assign array elements based on newlines. It will still be one string, just with a newline in the middle.

    – roaima
    5 hours ago













  • @Christopher I like your solution but gave me a headache :), because subsecuents comands use the IFS set before... it took me some time to figure what was happening, it does it silently.

    – guillermo chamorro
    3 hours ago











  • var=$(...) is equivalent to var="$(...)"

    – Jesse_b
    2 hours ago














  • 1





    Try echo "${#usbs[@]}" to see the number of items in the usbs "array", or "${!usbs[@]}" to list its indices. Or print it with echo "$usbs". It is likely storing what you are expecting it to.

    – fra-san
    5 hours ago








  • 1





    Double-quote your variables (and $(...) constructs) when you reference them and the shell will keep your whitespace intact. But be aware the shell won't automatically assign array elements based on newlines. It will still be one string, just with a newline in the middle.

    – roaima
    5 hours ago













  • @Christopher I like your solution but gave me a headache :), because subsecuents comands use the IFS set before... it took me some time to figure what was happening, it does it silently.

    – guillermo chamorro
    3 hours ago











  • var=$(...) is equivalent to var="$(...)"

    – Jesse_b
    2 hours ago








1




1





Try echo "${#usbs[@]}" to see the number of items in the usbs "array", or "${!usbs[@]}" to list its indices. Or print it with echo "$usbs". It is likely storing what you are expecting it to.

– fra-san
5 hours ago







Try echo "${#usbs[@]}" to see the number of items in the usbs "array", or "${!usbs[@]}" to list its indices. Or print it with echo "$usbs". It is likely storing what you are expecting it to.

– fra-san
5 hours ago






1




1





Double-quote your variables (and $(...) constructs) when you reference them and the shell will keep your whitespace intact. But be aware the shell won't automatically assign array elements based on newlines. It will still be one string, just with a newline in the middle.

– roaima
5 hours ago







Double-quote your variables (and $(...) constructs) when you reference them and the shell will keep your whitespace intact. But be aware the shell won't automatically assign array elements based on newlines. It will still be one string, just with a newline in the middle.

– roaima
5 hours ago















@Christopher I like your solution but gave me a headache :), because subsecuents comands use the IFS set before... it took me some time to figure what was happening, it does it silently.

– guillermo chamorro
3 hours ago





@Christopher I like your solution but gave me a headache :), because subsecuents comands use the IFS set before... it took me some time to figure what was happening, it does it silently.

– guillermo chamorro
3 hours ago













var=$(...) is equivalent to var="$(...)"

– Jesse_b
2 hours ago





var=$(...) is equivalent to var="$(...)"

– Jesse_b
2 hours ago










1 Answer
1






active

oldest

votes


















6














This is a good situation to use readarray/mapfile:



readarray -t usbs < <(lsblk -o NAME,TRAN,VENDOR,MODEL | grep usb)


This will create an array with your output where each line is separated into it's own element.



In your case it would make an array like:



usbs=(
'sdb usb Kingston DataTraveler 2.0'
'sdc usb Kingston DT 101 G2'
)




As is you are assigning your entire output to a single variable (not an array) which essentially does this:



usbs='sdb   usb    Kingston DataTraveler 2.0
sdc usb Kingston DT 101 G2 '




In order to make it an array you would do:



usbs=($(lsblk -o NAME,TRAN,VENDOR,MODEL | grep usb))


but this would make each word separated by whitespace into its own element, equivalent to:



usbs=(
sdb
usb
Kingston
DataTraveler
2.0
sdc
usb
Kingston
DT
101
G2
)





share|improve this answer
























    Your Answer








    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "106"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });






    guillermo chamorro is a new contributor. Be nice, and check out our Code of Conduct.










    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f519140%2fiterate-lines-of-string-variable-in-bash%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    6














    This is a good situation to use readarray/mapfile:



    readarray -t usbs < <(lsblk -o NAME,TRAN,VENDOR,MODEL | grep usb)


    This will create an array with your output where each line is separated into it's own element.



    In your case it would make an array like:



    usbs=(
    'sdb usb Kingston DataTraveler 2.0'
    'sdc usb Kingston DT 101 G2'
    )




    As is you are assigning your entire output to a single variable (not an array) which essentially does this:



    usbs='sdb   usb    Kingston DataTraveler 2.0
    sdc usb Kingston DT 101 G2 '




    In order to make it an array you would do:



    usbs=($(lsblk -o NAME,TRAN,VENDOR,MODEL | grep usb))


    but this would make each word separated by whitespace into its own element, equivalent to:



    usbs=(
    sdb
    usb
    Kingston
    DataTraveler
    2.0
    sdc
    usb
    Kingston
    DT
    101
    G2
    )





    share|improve this answer




























      6














      This is a good situation to use readarray/mapfile:



      readarray -t usbs < <(lsblk -o NAME,TRAN,VENDOR,MODEL | grep usb)


      This will create an array with your output where each line is separated into it's own element.



      In your case it would make an array like:



      usbs=(
      'sdb usb Kingston DataTraveler 2.0'
      'sdc usb Kingston DT 101 G2'
      )




      As is you are assigning your entire output to a single variable (not an array) which essentially does this:



      usbs='sdb   usb    Kingston DataTraveler 2.0
      sdc usb Kingston DT 101 G2 '




      In order to make it an array you would do:



      usbs=($(lsblk -o NAME,TRAN,VENDOR,MODEL | grep usb))


      but this would make each word separated by whitespace into its own element, equivalent to:



      usbs=(
      sdb
      usb
      Kingston
      DataTraveler
      2.0
      sdc
      usb
      Kingston
      DT
      101
      G2
      )





      share|improve this answer


























        6












        6








        6







        This is a good situation to use readarray/mapfile:



        readarray -t usbs < <(lsblk -o NAME,TRAN,VENDOR,MODEL | grep usb)


        This will create an array with your output where each line is separated into it's own element.



        In your case it would make an array like:



        usbs=(
        'sdb usb Kingston DataTraveler 2.0'
        'sdc usb Kingston DT 101 G2'
        )




        As is you are assigning your entire output to a single variable (not an array) which essentially does this:



        usbs='sdb   usb    Kingston DataTraveler 2.0
        sdc usb Kingston DT 101 G2 '




        In order to make it an array you would do:



        usbs=($(lsblk -o NAME,TRAN,VENDOR,MODEL | grep usb))


        but this would make each word separated by whitespace into its own element, equivalent to:



        usbs=(
        sdb
        usb
        Kingston
        DataTraveler
        2.0
        sdc
        usb
        Kingston
        DT
        101
        G2
        )





        share|improve this answer













        This is a good situation to use readarray/mapfile:



        readarray -t usbs < <(lsblk -o NAME,TRAN,VENDOR,MODEL | grep usb)


        This will create an array with your output where each line is separated into it's own element.



        In your case it would make an array like:



        usbs=(
        'sdb usb Kingston DataTraveler 2.0'
        'sdc usb Kingston DT 101 G2'
        )




        As is you are assigning your entire output to a single variable (not an array) which essentially does this:



        usbs='sdb   usb    Kingston DataTraveler 2.0
        sdc usb Kingston DT 101 G2 '




        In order to make it an array you would do:



        usbs=($(lsblk -o NAME,TRAN,VENDOR,MODEL | grep usb))


        but this would make each word separated by whitespace into its own element, equivalent to:



        usbs=(
        sdb
        usb
        Kingston
        DataTraveler
        2.0
        sdc
        usb
        Kingston
        DT
        101
        G2
        )






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 5 hours ago









        Jesse_bJesse_b

        15.3k33574




        15.3k33574






















            guillermo chamorro is a new contributor. Be nice, and check out our Code of Conduct.










            draft saved

            draft discarded


















            guillermo chamorro is a new contributor. Be nice, and check out our Code of Conduct.













            guillermo chamorro is a new contributor. Be nice, and check out our Code of Conduct.












            guillermo chamorro is a new contributor. Be nice, and check out our Code of Conduct.
















            Thanks for contributing an answer to Unix & Linux Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f519140%2fiterate-lines-of-string-variable-in-bash%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Taj Mahal Inhaltsverzeichnis Aufbau | Geschichte | 350-Jahr-Feier | Heutige Bedeutung | Siehe auch |...

            Baia Sprie Cuprins Etimologie | Istorie | Demografie | Politică și administrație | Arii naturale...

            Nicolae Petrescu-Găină Cuprins Biografie | Opera | In memoriam | Varia | Controverse, incertitudini...