Find the answer to your Linux question:
Results 1 to 4 of 4
Hi, I'm pretty new to using things like awk/sed, but have managed to cobble together what I needed so far without a problem. The only thing I'm struggling with is ...
  1. #1
    Just Joined!
    Join Date
    May 2010
    Posts
    2

    Can't figure out assigning a variable for later use in shell script

    Hi,

    I'm pretty new to using things like awk/sed, but have managed to cobble together what I needed so far without a problem. The only thing I'm struggling with is to assign the content of a particular line as a variable, and then to use it again throughout the file.

    For example, if what I want is the first line of the file to become the variable "from1", and then to replace the word "Subject" in the file with the string "Message from [from1]".
    What I thought would work

    #!/bin/bash

    from1="$(awk 'NR==1')" test.txt

    sed -i "s/Subject/Message from $from1/g" test.txt


    I tried a few diff combinations but nothing seems to work. All I get is the terminal hanging indefinitely. Is there something really obvious that I'm missing? (sorry if it's really blatant, I have tried looking for the answer but can't find anything)

    D

  2. #2
    Trusted Penguin Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,230
    It's not that your terminal is hanging, it's that you are running awk and it is waiting for input. This is because the way that you are calling awk is not telling it the input to run against.

    First off, let's not use awk. awk is a very powerful program, and for this problem (find the first line), there's a much simpler way:
    Code:
    head -n1
    This prints the first line of a file.

    So let's rewrite the script now:
    Code:
    #!/bin/bash
    
    from1=$(head -n1 test.txt)
    sed -i "s/Subject/Message from $from1/g" test.txt
    Does this make sense? Do you understand the difference between this and the one that you posted?
    DISTRO=Arch
    Registered Linux User #388732

  3. #3
    Just Joined!
    Join Date
    May 2010
    Posts
    2

    Thanks!

    Hi, thanks a million for the advice. I get now why awk was a bad option.

    Theoretically, if I wanted to grab from the second line instead, what would be my best command? cut?

  4. #4
    Trusted Penguin Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,230
    cut is designed to take in lines of input and split each line into various fields. For selecting specific lines, the best bet is probably sed:
    Code:
    sed -n '2 p'
    What this does is tell sed to use quiet output (so it only prints lines that you tell it to). You then give it a rule that says to print line number 2.
    DISTRO=Arch
    Registered Linux User #388732

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...