w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
linux Bash - read contents of file , store them in a variable and create network config file
I tried yesterday and I am very close to the solution. Researching the internet , I made a perl script and was able to create multiple interface by extracting data from csv file. But there is small issue I see and not able to figure out why an extra character is coming in the file. Following is the code: #!/usr/bin/perl use strict; use warnings; sub main { # Note: this could be a full file path my $filename = "file1.csv"; open(INPUT, $filename) or die "Cannot open $filename"; # Read the header line. #my $line = <INPUT>; my $line; # Read the lines one by one. while($line = <INPUT>) { chomp($line); # Display the header, just to check things are working.

Categories : Linux

bash expand variable in a variable, with $ as prefix
The more idiomatic way of iterating over the positional parameters is to use $@: for p in "$@"; do GET_BLOCK "/$p/" done What you wanted was for ((i=1; i<$#; i++)) do GET_BLOCK "/${!i}" done but this is both non-standard and less clear than iterating over $@ directly.

Categories : Bash

Bash: update variable that uses a updated variable
Instead of a string, you should use a shell function: function startecho() { date +%F_%T ; echo " dobackup.sh | Backup $bc started!" ; } function endecho() { date +%F_%T ; echo " dobackup.sh | Backup $bc ended!" ; } startecho endecho bc=$((bc+1)) startecho endecho

Categories : Bash

In bash, how to use a variable as part of the name of another variable?
You can use eval: #!/bin/bash array_0=(1 2 3) array_1=(4 5 6) array_2=(7 8 9) for a in {0..2} ; do for i in {0..2} ; do eval 'echo ${'"array_$a[$i]"'}' done done Vaughn Cato's syntax is slightly more verbose, but the echo statement itself is more decipherable. You replace the inner part of the double for loop with these two lines: array_a=array_$a[$i] echo ${!array_a}

Categories : Bash

Trouble with single digit value in getting the value from a URL variable
Remove $ from href$ and try like this $("#menuContainer a[href=" + cat + "]").parent().parent().parent().find("H3").text(); demo jsfiddle with href$ in this fiddle when you click on "Click here - 3", it should alert 3 but it will alert 31323. Because href$ if finding and concatenating 3, 13 and 23 demo jsfiddle with href in this link it works as expected and alert 3

Categories : Jquery

Store smarty variable in PHP variable
where exactly do you want it to work? in php $var = $this->_tpl_vars['v']['user_id']; or in smarty {assign var="var" value=$v.user_id}

Categories : PHP

BASH: how to define an array as environment variable before calling a bash script
Incredibility weird.... I have never seen that before. It looks like the array is not passed to the subshell. One way around this is to source the script instead of executing it: declare -a MYARR=( 1 2 ); . ./myscript.sh

Categories : Arrays

How to check if the numbers smaller than an integer variable contain a specific digit
I have no idea what your intention was with this code: wholenumber = 3 % 10; wholenumber = 3 / 10; First line sets the variable to 3, the second to 0.. which forces the program to exit from the loop.

Categories : C

Unable to increment last 2 digit of variable declared in file using script
If you're using vim, then you can use the sequence: /RSTATE/ $<C-a>:x The first line is followed by a return and searches for RSTATE. The second line jumps to the end of the line and uses Control-a (shown as <C-a> above, and in the vim documentation) to increment the number. Repeat as often as you want to increment the number. The :x is also followed by a return and saves the file. The only tricky bit is that the leading 0 on the number makes vim think the number is in octal, not decimal. You can override that by using :set nrformats= followed by return to turn off octal and hex; the default value is nrformats=octal,hex. You can learn an awful lot about vim from the book Practical Vim: Edit Text at the Speed of Thought by Drew Neil. This information comes from Tip 10

Categories : Shell

Run a bash including a variable in the "bash XXX.sh" command
You can take advantage of shell parameter expansion to smoothly read variables from the environment of the parent process, if it's that what you want to achieve. Look at the following script named test.sh: #!/bin/bash VARIABLE=${VARIABLE:="default value"} echo $VARIABLE If you start it with the line $ ./test.sh it outputs default value But if you invoke test.sh with the line $ VARIABLE="custom Value" ./test.sh it outputs custom value But make sure that the variable assignment is at the beginning of the line. Otherwise it is passed to test.sh as command line argument. The used form of parameter expansion ${parameter:=word} is described in the bash reference manual as: If parameter is unset or null, the expansion of word is assigned to parameter. The value of param

Categories : Bash

To find factorial of 500 and store it in a variable...and perform calculations...How to store such a huge number?
There is no built-in language support for such large numbers. You have two options: if you can, use existing library, like GMP implement you own solution If you decide to take the second path, you might want to consider storing digits (not necesserily decimal) in an array, and perform arithmetic operations using well known school algorithms. Keep in mind it will be (probably considerably) less efficient than heavily optimized library code.

Categories : C

Jquery How to use .click() to update a variable and pass that variable to an array or add it to another variable
In this case the alert will show undefined since it is executed before the actual click happens. But the value of v1PackCharge is globally set, you can use it outside the click handler. Only thing is you need to modify the test case Demo: Fiddle

Categories : Jquery

AS3 Advanced Variable Usage - Retrieve Value In Variable Selected Based On Value In Another Variable
Generally not a fan of having data-defining element names in XML, but - assuming event.dat is actually an XML object, and not an arbitrary object that you've manually parsed the XML into (can't tell from the question) - this is really a question about ECMAScript for XML (E4X) rather than variables in general. If so, this should work: for each (var menuField:XML in event.dat.child(mnVariable).element) { // Do something } Can't test at the moment, but this may also work (it's part of E4X standard, but not sure if Adobe implemented it): // Note, no dot before the indexer: for each (var menuField:XML in event.dat[mnVariable].element) { // Do something } The latter is also generally the way to access a property of an object using a string property name, so if event.dat is an arbitr

Categories : Actionscript

Store value of php array variable to javascript array variable
You need to start out with a php array that mirrors the javascript array that you want. Then output the results of json_encode on that array. For this I am assuming you want an array of arrays. <?php $coorStr = "-7.175993,112.650729|-7.17616,112.651139|-7.176591,112.650968|-7.176413,112.650552|-7.176104,112.650437','-7.176331,112.649924|-7.17632,112.650053|-7.176629,112.650048|-7.176629,112.649914"; $coor= explode("|",$coorStr); $coor = array_map(function($a) { return explode(",", $a); }, $coor); ?> allcoor = <?php echo json_encode($cobadeh); ?>; The first explode command splits the string into an array of elements containing each of the coordinate pairs. The array_map call splits each of element in an array. Finally the json_encode formats the data correctly for a j

Categories : PHP

^H in bash variable
The backspace just moves the cursor one position to the right without actually erasing what's printed on the screen. Only your second instruction actually erases the 4th character by overwriting it with the trailing space in your string. I'll try to visualize it: $ echo "hello^H^H" hello ^ `-- cursor position $ echo "hello^H^H " hel o ^ `-- cursor position

Categories : Bash

Extract array from one json variable
Use var category = dataset.map( function( obj ) { return obj.category; } ); var popularity = dataset.map( function( obj ) { return obj.popularity; } ); The category and popularity arrays will contain the values you need. However, a for loop is likely to be a faster implementation.

Categories : Javascript

Extract a bytearray variable using C# DotNetZip
If what you're trying to do is decompress data that has been compressed using zlib, I would suggest using the ZLib.NET library: http://www.componentace.com/zlib_.NET.htm It would depend on what you want to do with the data; but, here's an example of using a Stream with DotNetZip: using (var input = new ZipInputStream(new MemoryStream(zipBytes))) { ZipEntry e; while ((e = input.GetNextEntry()) != null) { if (e.IsDirectory) continue; using (var output = File.Open(e.FileName, FileMode.Create, FileAccess.ReadWrite)) { while ((n = input.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, n); } } } }

Categories : C#

Extract part of the string to another variable
This is not perfect as the comments state but for your text this would work. if you have some one with 1/3 or more parts to there name it would mess up but for your example this will do the trick $text = "John Doe Designer Another Name AnotherJob"; $parts = explode(" ", $text); $persons = array(); foreach($parts as $key => $part){ $personData = explode(" ", $part); $job = str_replace($personData[0]." ".$personData[1], "", $part); $persons[] = array( "fname" => $personData[0], "lname" => $personData[1], "job" => $job ); } print_r($persons);

Categories : PHP

How to extract this string variable in android?
You could split on a simple regex: String [] splitStrings = test.split("\],\["); You don't want to split on just comma because you only want the commas between the square brackets. Here is a more complete example (and a regex that holds onto the brackets if you want) public static void main(String []args){ String test="["1","Low-level programming language",true],["2","High level programming language",false],["3","Machine language",false],["4","All of the above",false],["5","None of these",false]"; String [] splitStrings = test.split("(?!\]),(?=\[)"); System.out.println(splitStrings[0]); System.out.println(splitStrings[1]); System.out.println(splitStrings[2]); System.out.println(splitStrings[3]); System.out.println(splitStrings[4]); }

Categories : Java

Extract number from a variable in powershell
Something like this should work: # initialize the variable that we want to use to store the port numbers. $portList = @() # foreach object returned by GetPortNames... [IO.Ports.SerialPort]::GetPortNames() | %{ # replace the pattern "COM" at the beginning of the string with an empty # string, just leaving the number. Then add the number to our array. $portList += ($_ -ireplace "^COM", [String]::Empty) } Note that I used [IO.Ports.SerialPort] instead of [System.IO.Ports.SerialPort]. These are the same things - PowerShell implicitly assumes that you're working with the [System] namespace, so you don't need to specify it explicitly, though there's nothing wrong with doing it. Edit To answer your questions: %{...} is shorthand for foreach-object {...}. $_ indicates the obj

Categories : Regex

search variable and corresponding value in bash
All together: $ data=$(grep -nPo '(?<=delay=)d+' file | sort -rn -t: -k2 | head -1) $ line=${data%%:*} $ delay=${data##*:} $ awk -v line=$line -v delay=$delay 'NR==line {print "longest delay was **", delay, "** on", $1, $2, "at", $3, "at server",$4, " ",$0}' file longest delay was ** 162708 ** on Jul 16 at 00:01:43 at server abc Jul 16 00:01:43 abc postfix/smtp[28815]: F19Dwq003: to=<sullcrom@em1.SulivanCromwell.com>, relay=em1.SullivanCromwell.com[223.222.222.2]:25, delay=162708, delays=162705/0.3/1.6/0.62, dsn=4.2.2, status=deferred (host em1.SullivanCromwell.com[223.222.222.2] said: 452 4.2.2 Mailbox full (in reply to RCPT TO command)) Explanation (spoiler: it can be boring) You can firstly get the following: $ grep -nPo '(?<=delay=)d+' file | sort -rn -t: -k2 3:16

Categories : Bash

Is it possible to use a variable in for syntax in bash?
It is not possible to use variables in the {N..M} syntax. Instead, what you can do is use seq: $ var=5 $ for i in $(seq 1 $var) ; do echo "$i"; done 1 2 3 4 5 Or... $ start=3 $ end=8 $ for i in $(seq $start $end) ; do echo $i; done 3 4 5 6 7 8

Categories : Bash

How to get expect to set a bash variable
I don't know Expect, but I think it's something like this SSH_SUCCESS=$(expect <<EOF ... expect { "0" { puts "PASSED" } "1" { puts "FAILED" } ... EOF ) echo $SSH_SUCCESS

Categories : Bash

How do i populate this variable in bash?
To prevent substitution, you can use either single-quotes '...' or a backslash ; for example, this command: echo '$foo' $foo "$foo" will print this: $foo $foo $foo and will not use the variable foo. In your case, rather than using "..." for the whole argument, you probably should use '...' everywhere except where you specifically need substitution. So: HOST=foo DIR=bar ssh user@$HOST ' function test { CURHOST='"$HOST"' cd $DIR mkdir -p $CURHOST }; test'

Categories : Bash

Failure of Bash $@ variable
You need to double-quote the $@to keep bash from performing the unwanted parsing steps (word splitting etc) after substituting the argument values: function Foobar { cmd -opt1 -opt2 "$@" } EDIT from the Special Parameters section of the bash manpage: @ Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" ... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the begin- ning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ e

Categories : Bash

BASH: sed -e not allowing my variable
Just use awk, it has less caveats linenumber=$(awk -v p="$player" '$0 ~ p { print NR }' "$outputfile") awk -v n="$linenumber" 'NR == n { sub(/2013-08-25/,"test") }1' "$outputfile" and of course you don't need multiple steps: awk -v p="$player" '$0 ~ p{ sub(/2013-08-25/,"test") }1' "$outputfile" To write the output back to your input file: awk 'script' "$outputfile" > tmp && mv tmp "$outputfile" The above does the same thing sed does, it's just that you specify the tmp file instead of sed coming up with one for you. If you'd rather have awk do that for you then with recent gawk versions you can do: awk -i inedit 'script' "$outputfile" Whatever. It is NOT worth giving up awk simplicity and functionality to avoid the triviality of creating your own tmp file.

Categories : Bash

how to set file as a variable in bash
If you know there are exactly 14 files, do this: for i in {1..14}; do clustalo -i home/my_directory/$a.fasta -o home/my_directory/$b.aln done If you want to process all of the *.fasta files, however many there are, then do: for file in home/my_directory/*.fasta; do clustalo -i "$file" -o "${file%.fasta}.aln" done To understand this, ${file%.fasta} gives us $file with the .fasta extension stripped off. If you want to store the file names in a variable first, the best thing to do is to use an array variable. You do that by adding parentheses around the variable assignment, and then accessing the array values with the strange syntax "${array[@]}". files=(home/my_directory/*.fasta) for file in "${files[@]}"; do clustalo -i "$file" -o "${file%.fasta}.aln" done

Categories : Bash

How to grep using a variable in bash
You should quote it grep "$GTUNNELNATNETIP" iptables2.out Read more about quoting variables in bash This must work. I cannot reproduce your trailing backslash error, but most probably you have some garbage in $GTUNNELNATNETIP variable

Categories : Regex

How to copy local variable to global variable if both have the same names in C without using a third variable?
What you're doing is "shadowing" the global variable. In order to unshadow it in a local block, declare it in its own nested block with extern. void myFunction() { int myVariable { extern int myVarible; //modify myVariable global here; } //modify myVariable localhere }

Categories : C

how to extract ip address from string variable in javascript
Try this: function reg() { var a="ec2-54-234-174-228.compute-1.amazonaws.com"; var r = a.match(/-[0-9-]*/g); alert(r[0].substring(1,r[0].length)); } a.match(/-[0-9-]*/g); will return [-54-234-174-228,-1]. Getting the first element and removing - from the beginning you get what your IP. You can also add this: alert(r[0].substring(1,r[0].length).replace(/-/g, '.')); to return it in IP shape: 54.234.174.228

Categories : Javascript

How do I perform this regex in order to extract the value of the variable
If you are using PHP or PERL or more generally PCRE then you can use the K flag to solve this problem like this: dtimes+=sK[-+]?[0-9]*.?[0-9]+([eE][-+]?[0-9]+)? ^^ Notice the K, it tells the expression to ignore everything behind it as if it was never matched Regex101 Demo Edit: I think you need to capture the number in a capturing group if you can't use look behinds or eliminate what was matched so: dtimes*=s*([-+]?[0-9]*.?[0-9]+([eE][-+]?[0-9]+)?)

Categories : Regex

Extract data from HTML code in PHP variable
I would rather use more input with hidden type and give them appropriate names like: <tr class="tr1"> <td align="right">1.</td> <input type="hidden" name="position" value="1" /> <input type="hidden" name="id" value="765434" /> <input type="hidden" name="value" value="89898989" /> <input type="hidden" name="price" value="100" /> <td>Some description</td> </tr> It will be much easier to maintain such code and you will have no problem with accessing variables in php. I'm sorry if this is now you are asking for but for me it's reasonable solution (I may not know all the facts). If you are not able to change this HTML I recommend you to check SimpleHTMLDom library instead of xpath here are some info: http://simplehtmldom.sourcefor

Categories : PHP

How can I use Robotium Test to extract variable value of a Fragment?
I think i cover most of this here: How do I get a reference to a fragment from within a unit/robotium test? but there is one thing that does not cover, and that is that you will have to unsafely cast the fragment you receive into the fragment class that you have a method to call in order to get the value or alternatively use reflection on the fragment returned to peek into the internal state (I vote you go for option one)

Categories : Android

Powershell - now to extract name of variable passed to script
If I were you I would probably start with looking at actual input to your script when your program runs... If it will however just do: .yourscript.ps1 -foo-bar something -something-else value -sender-ip yourdata You can get the value of sender-ip very easily: param ( ${sender-ip} ) "Sender IP = ${sender-ip}" If that's not the case you will probably have to paste here what you get when you do simple $args in your script. Without seeing what is there it may be hard to suggest something similar to thing that python does... EDIT In case you receive data as name=value pairs, try this: function foo { $hash = ConvertFrom-StringData -StringData ($Args -Join "`n") $hash.'sender-ip' } foo test-first=alfa sender-ip=beta In my test I got expected (beta) result...

Categories : Python

R - extract variable names from unevaluated expression
The "left hand side" of expression(x=y+z) is actually the name of the argument you're passing to expression(), whose value is the (unevaluated) call y + z. So it's not a part of the expression, but is returned as the name of the list element (an expression is a list of calls, usually unnamed): > as.list(expression(x=y+z)) $x y + z > names(expression(x=y+z)) [1] "x" If, OTOH, you use the formula constructor ~, then you get the LHS as a part of the expression: > as.list(expression(x~y+z)) [[1]] x ~ y + z And you can get to it selecting the second element of the call: > expression(x~y+z)[[1]] x ~ y + z > expression(x~y+z)[[1]][[1]] `~` > expression(x~y+z)[[1]][[2]] x Note: in the last line, x is a symbol.

Categories : R

How to extract data by matching a variable with the tag value in python
It seems the best way to extract speaker and text information is to extract all ids in a list and all speaker info in another list. Then just cross-reference the ids needed and get the corresponding speaker info. I create a dictionary here with key as ids and value as speaker info. I found the speaker info by the condition that the td field has a style attribute defined in all fields containing speaker info. For extracting info from HTML, I am using the BeautifulSoup library. from bs4 import BeautifulSoup from itertools import izip soup = BeautifulSoup(open('table.html')) idList = [] speakerList = [] idsRequired = ['abc1','abc2'] for a in soup.findAll('a'): if 'id' in a.attrs.keys(): idList.append(a.attrs['id']) for i in soup.findAll('td'): if 'style' in i.attrs.k

Categories : Python

How to extract a javascript variable using regular expression
If you look at the docs for re.findall(pattern, string, flags=0), you'll see you need to change how you're using it affiliates = re.findall('var affiliates = (.*?);s*$', result.read(), re.M) You might also want to consider how whitespace can be sloppy in JavaScript.

Categories : Javascript

Would like to take a Perl variable and pass it to bash
You can run all external programs and commands from Perl with system, exec and the backtick-operator (`` and qx()). Please refer to: http://perldoc.perl.org/functions/system.html http://perldoc.perl.org/perlop.html#%60STRING%60 http://perldoc.perl.org/functions/exec.html If you want to, say, copy stuff to another server, you can use the backticks like this: my $file = 'foo.csv'; `scp foo.csv someone@otherserver:dir/foo.csv`;

Categories : Perl

Bash Shell: Cannot use variable $ as a path to run tar
~ doesn't expand to your home directory in double quotes. Just remove the double quotes: backup_source=~/momobobo backup_dest=~/momobobo_backup/ In cases where you have things you would want to quote, you can use ~/"momobobo"

Categories : Linux

bash variable - escaping point
It works for me. You are probably not quoting the variable when using it later: M2_1="GRANT USAGE ON *.* TO '$USER'@'%' IDENTIFIED BY PASSWORD '$MYSQL_PASSWORD';" echo "$M2_1"

Categories : Bash



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.