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 ...
- 05-04-2010 #1Just 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
- 05-04-2010 #2
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:
This prints the first line of a file.Code:head -n1
So let's rewrite the script now:
Does this make sense? Do you understand the difference between this and the one that you posted?Code:#!/bin/bash from1=$(head -n1 test.txt) sed -i "s/Subject/Message from $from1/g" test.txt
DISTRO=Arch
Registered Linux User #388732
- 05-04-2010 #3Just 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?
- 05-05-2010 #4
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:
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.Code:sed -n '2 p'
DISTRO=Arch
Registered Linux User #388732


Reply With Quote