Pull string from a file into a variable using bash
The subject explains it really... i have a file (.tmpfile) and inside it is a string which i only know part of, the rest being a random group of characters... I would like to know how to pull the whole string out of the file and into a variable.
Thanks in advance... |
Hi and welcome to LQ,
Try this: var=$(sed -rn 's/.*([^[:blank:]]*variable[^[:blank:]]*).*/\1/p' file) If that does not do the trick then you will have to post the file and what exactly you want to extract |
Hello and Welcome to LinuxQuestions,
You could use grep for that. Since grep is greedy it will save the whole line where the regex is encountered. It would help though if you could include an example of your 'string'. For example if I have a file which has among other lines the following text: Code:
This is a simplistic regular regex grep Code:
VARIABLE=$(grep simplistic <yourfilename.tmpfile>) Looking forward to your participation in the forums. Have fun with Linux. Kind regards, Eric |
Thanks for the welcome guys :)
Crts, thank you for that i'll try that in a second... and Eric, it wasn't quite like that... should have been more specific, i need to pull 100000597065197 from : Code:
<dict> I know the key tag is malformed, ive already pulled this section of code from a different file... |
Hi,
No problem at all. That only happens if you ask a questions with a broad possibility of answers. The more specific your questions, the more defined the answer. From your example you could use, in line with what ctrs posted: Code:
VARIABLE=$(sed -i ‘s#.*<key>\(.*\)<\/key>.*#\1#g' yourfile) Hope it helps. Kind regards, Eric |
Quote:
Code:
var=$(sed -rn 's|.*<key>(.*)</key>|\1|p') |
Careful!
Quote:
@Eric: The '-i' option will prevent any output, so VARIABLE would be empty afterwards. |
Quote:
You're absolutely right! I'm sorry. I just copied part of a full line without even thinking. This is what it should have been: Code:
VARIABLE=$(cat yourfile | grep "<key" | sed 's#.*<key>\(.*\)<\/key>.*#\1#g') EDIT: your solution looks so much neater! Yet learned other ways. Thanks. Kind regards, Eric |
Quote:
slightly confused, which one am i doing? Sorry again people... |
Quote:
As pointed out by crts, don't use that one. I goofed up :( The second one should work though, but the solutions offered by crts look a lot better and less typing. Kind regards, Eric |
Thanks again Eric and crts,
Quote:
|
Quote:
At the end of the line just before the closing ). Kind regards, Eric |
Again Thank you both :) how do i up your rep? :)
|
Hi,
Already 'upped' apparently. Thanks. Glad you've got a solution. And thanks for marking your thread solved. Have fun with Linux. Kind regards, Eric |
All times are GMT -5. The time now is 04:09 PM. |