Creating String from words in a file
Hi i have a file called search.txt
Which contains text like Car Bus Cat Dog Now i have to create a string from the file which should look like Car,Bus,Cat,Dog ( appending , is essential part) String must be stored in some variable so i can pass it as argument to some other command. Thnx in advance |
That's a nice learning exercise :)
What have you tried so far? |
Yes it does look like a good exercise. What did your professor tell you to use?
bash sed awk tr perl C C++ Java To name a few. |
i need to write a script
bash awk sed any of three will do .. |
So, what did you try? Show us some evidence you've actually put a bit more effort in than just posting to the first Linux forum you found on the internet.
|
for i in 1 2 3 4
do var1=$(awk '{print $i}') var2=',' var3=$var1$var2 done cat var3 |
Have a look into tr. You can translate a particular character (in this case, I suggest a newline represented by \n) into another charater, a comma. Storing the output of a command as a variable is achieved through the use of $() in bash. So, if I wanted to store the output of the date command as a variable called currentDate, I'd do the following:
Code:
currentDate=$(date) Hope this helps. |
while read line
do var1=$(awk '{print $NF}') var2=',' var3=$var1$var2 done cat var3 |
if some body has a solution plz share ....
|
If you insist on using the approach of a loop, then you should know that you don't cat a variable, you echo it. And calling a variable requires that you prefix its name with a $. For example:
Code:
echo $var3 edit: As an extra hint, your while loop doesn't have any input. Try adding < search.txt after done. |
while read line
do var1=$(awk '{print $NF}') var2=',' var3=$var1$var2 done < search.txt echo $var3 |
c++
c++ is only one i know, first draft-see if it works
#include <ifstream> #include <string> #include <iostream> main() { ifstream fileinput; string varfile; int numOfVars = 4; //because 4 variables u need to read fileinput.open("textfile.txt"); for(count=0;count<numOfVars;count++) // executes 4 times { fileinput>>varfile; //reads first string from textfile.txt endfile = endfile + varfile + ","; //adds varfile string to end of endfile } return 0; } in this case the string would be in variable endfile btw the end of the string would have have a comma u can fix this with an if statement under |
Quote:
Code:
while read line |
Try adding
set -xv at the top to see what it's doing. |
In bash:
############### #!/bin/bash for item in $(cat search.txt) # put the output of cat <file> in a list for iteraction do result=$result$item, # That's the string concatenation "magic". Just try to understand, as I did. done echo $result # print the output ########### I'd have done it more stylish in perl, but that fills what you asked. |
All times are GMT -5. The time now is 08:07 AM. |