w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Verifying user input for a magic square game/Comparing arrays (user-defined&programmer-defined)
IMO you should maintain a multi-dimensional array for better code readability that is int[3][3] instead of 3 int[3]'s. Below is my try public static void main(String [] args) { int[][] input=new int[3][3]; int[][] defined={{8,1,6}, {3,5,7}, {4,9,2}}; Scanner sc=new Scanner(System.in); //Take input //Outer loop for(int i=0; i<3; i++) { System.out.println("Enter value for Row number - "+(i+1)); //Inner loop for(int j=0; j<3; j++) { input[i][j] = sc.nextInt(); } } //Compare boolean matches = true; for(int i=0; i<3; i++) { //Inner loop for(int j=0; j<3; j++) { if(input[i][j] != defined[i][j]) { matches = false; break; }

Categories : Java

Bash script to grep through one file for a list names, then grep through a second file to match those names to get a lookup value
awk -v search="$search_string" '$0 ~ search { gsub(/"/, "", $5); print $1" "$5; }' "$filename" | while read line do result=$(awk -v search="$line" '$0 ~ search { print $3; } ' "$lookup_file"); # Do "something" with $result 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

Grep (Bash) error
It's because you're trying to grep for something like -4.5 and grep is treating that as an option rather than a search string. If you use -- to indicate there are no more options, this should work okay: pax> echo -4.5000000000E-01 | grep -4.5000000000E-01 grep: invalid option -- '.' Usage: grep [OPTION]... PATTERN [FILE]... Try 'grep --help' for more information. pax> echo -4.5000000000E-01 | grep -- -4.5000000000E-01 -4.5000000000E-01 In addition, if you pass the string 7.2 to grep, it will match any line containing 7 followed by any character followed by 2 since: Regular expressions treat . as a special character; and Without start and end markers, 7.2 will also match 47.2, 7.25 and so on.

Categories : Bash

How to use variables in bash grep?
You are using single quotes which would prevent expansion of the variable. Use double quotes: grep -oP "name : ${dbname}d*" If you also want to match quotes " in the pattern, escape those: grep -oP ""name" : "${dbname}d*""

Categories : Bash

bash script for conditional grep
This will do the trick : parity=0 for val in $(grep -E "errorCode|id" x.json|grep -Eo [0-9]+) do if [ $parity -eq 0 ] then if [ $val -eq 1 ] then parity=1 fi else echo "id $val is erroneous" parity=0 fi done where x.json is the jason file.Replace the line containing echo command with a suitable statement as per your requirement. For example, if you are appending the id to a error log, try : echo $val >> erroneousIDs.log NB : I assumed that the ordering of the fields will always be the same.

Categories : Linux

"/bin/grep: Unmatched [ or [^" in bash loop
First, check if ls is aliased to something. Maybe you should use the absolute path to ls and without any options. Make sure it is not system-aliased to color-ls or something. Second, you can change the loop header to for i in $MY_BIN_PATH/* and that may fix it as well.

Categories : Bash

Grep multiple bash parameters
A safe eval could be a good solution #!/bin/bash if [[ $# -gt 0 ]]; then TEMP=("grep" "-e" ""$1"" "*") for (( I = 2; I <= $#; ++I )); do TEMP=("${TEMP[@]}" "|" "egrep" "-e" ""$${I}"") done eval "${TEMP[@]}" fi To run it: bash script.sh A B C

Categories : Linux

I'd like to grep the output of ifconfig in bash
use this: ONLINE=$(ifconfig | grep -cs 'status: active') cause without "$" what bash will return is the result of the command being successful or not and if it is successful it is always zero.

Categories : Bash

GREP between 2 strings without PERL
Given that in your sample text the text between the parans looks like an ip address, and that the rest of the text doesn't contain what looks like an ip address, you could simply omit the parans and look for IP addresses. This expression will match strings which look like IP addresses, and limits octet to numeric values from 0 to 255. (1[0-9]{2}|2[0-4][0-9]|25[0-5]|[1-9][0-9]|[0-9]).(1[0-9]{2}|2[0-4][0-9]|25[0-5]|[1-9][0-9]|[0-9]).(1[0-9]{2}|2[0-4][0-9]|25[0-5]|[1-9][0-9]|[0-9]).(1[0-9]{2}|2[0-4][0-9]|25[0-5]|[1-9][0-9]|[0-9]) root@mysystem:~# echo "My IP=(192.168.0.1):205 bla bla" | grep -oE '(1[0-9]{2}|2[0-4][0-9]|25[0-5]|[1-9][0-9]|[0-9]).(1[0-9]{2}|2[0-4][0-9]|25[0-5]|[1-9][0-9]|[0-9]).(1[0-9]{2}|2[0-4][0-9]|25[0-5]|[1-9][0-9]|[0-9]).(1[0-9]{2}|2[0-4][0-9]|25[0-5]|[1-9][0-9]|[0-

Categories : Regex

bash script with grep and cut : command not found
In this line: result=`$callResult >> grep 'RESPONSE CODE' | cut -d':' -f 2` You should be piping output to grep, not redirecting. Change it to this: result=`$callResult | grep 'RESPONSE CODE' | cut -d':' -f 2` Also, the syntax is a bit off, and you're better off avoiding backticks when possible. This is even better: result="$(echo ${callResult} | grep 'RESPONSE CODE' | cut -d':' -f 2)"

Categories : Bash

bash and grep: passing of regex parameter
Change regex="^'$1$'" to regex="^$1$" and $($cmd) to $cmd Here is a fixed version: #!/bin/bash DICT=/usr/share/dict/ngerman usage () { progname=$(basename "$0") echo "usage: $progname regex" } if [ $# -le 0 ]; then usage exit 1 fi regex="^$1$" cmd="grep -i $regex $DICT" echo "$regex" echo "$cmd" $cmd | while read -r word; do echo "$word" done But this script has potential problems. For example try running it as ./script 'asdads * '. This will expand to all files in a directory and all of them are going to be passed to grep. Here is a bit improved version of your code with correct quoting and also with bonus input validation: #!/bin/bash DICT=/usr/share/dict/ngerman usage () { progname=$(basename "$0") echo "usage: $progname regex" } if [ $# -le 0 ]

Categories : Regex

Using a bash script to grep an integer and compare it to another
This happens when there was no match, $score is then the empty string. A simple fix: #!/bin/bash for f in `ls $1/*.html` do score=`grep -o -P '(?<=ADJ. SCORE: )-?[0-9]?[0-9]' $f` if [ -z $score ] then echo "No match in '$f'" else if [ "$score" -lt 36 ] then cp "$f" "$2" fi fi done I think you also need to be more aware of quoting requirements in shell scripting.

Categories : Bash

How do I retrieve the header when I want to look at grep output of something in bash?
With awk: command | awk 'NR==1||/bla/' Thanks to @doubleDown for pointing out that {print} is unnecessary since it is the default action. With perl: command | perl -ne 'print if $.==1 or /bla/' (If you need perl irregular expressions, perl is probably available :) )

Categories : Bash

Easiest way to do "git grep" for multiple strings?
You didn't mention what operating system you're using, but if it's linux-like, you can write a "wrapper" script. Create a shell script named something like git-grep1 and put it in a directory that's in your $PATH, so git can find it. Then you can type git grep1 param1 param2... as if your script were a built-in git command. Here's a quick example to get you started: # Example use: find C source files that contain "pattern" or "pat*rn" # $ git grep1 '*.c' pattern 'pat*rn' # Ensure we have at least 2 params: a file name and a pattern. [ -n "$2" ] || { echo "usage: $0 FILE_SPEC PATTERN..." >&2; exit 1; } file_spec="$1" # First argument is the file spec. shift pattern="-e $1" # Next argument is the first pattern. shift # Append all remaining patterns, separating them with '--

Categories : GIT

How do I grep for strings with special characters like []?
You are right that [ and ] are special characters. Quote them with or use fgrep instead. The latter is plain string search: fgrep "$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']" ... You still need to quote $ though because it is otherwise interpreted by bash and other shells.

Categories : Linux

put awk or grep output to command line arguments in bash
In bash, you cannot set positional parameters in a way that the caller can read that value. If you want to 'return' a string from a function, you must write it to stdout, like so: function myfunc() { echo "test" } VAR=$(myfunc) When the above code is run, VAR will contain the string 'test'.

Categories : Bash

Using bash grep -Po regex fails if string has an underscore
Your regexp uses , which matches the boundary between word and non-word characters. The problem is that _ is a word character, and so are digits, so there's no boundary between _ and 2. You can use [^0-9][0-9]{4}.{1}[0-9]{2}.{1}[0-9]{2}[^0-9] instead. If the date can be at the beginning or end of the filename, use: ([^0-9]|^)[0-9]{4}.{1}[0-9]{2}.{1}[0-9]{2}([^0-9]|$)

Categories : Regex

Grep multiple strings on large files
In reflect to the above comments i done another test. Taked my file from md5deep -rZ command (size: 319MB). Randomly selected 100 md5 checksums (each 32chars long). The time egrep '100|fixed|strings' md5 >/dev/null time real 0m16.888s user 0m16.714s sys 0m0.172s for the time fgrep -f 100_lines_patt_file md5 >/dev/null the time is real 0m1.379s user 0m1.220s sys 0m0.158s Nearly 15times faster as egrep. So, when you get only 0.3 sec improvment betwen egrep and fgrep IMHO thats mean: your IO is to slow The computing time for egrep is not slowed by processor or memory but IO and (IMHO) therefore you don't get any speed improvement with fgrep.

Categories : Bash

Extract strings in a text file using grep
for line in `cat text.txt`; do grep $line input.txt >> output.txt; done Contents of text.txt: ABCB8 ABCC12 ABCC3 ABCC4 AHR ALDH4A1 ALDH5A1 Edit: A safer solution with while read: cat text.txt | while read line; do grep "$line" input.txt >> output.txt; done Edit 2: Sample text.txt: ABCB8 ABCB8XY ABCC12 Sample input.txt: You were hired to do a job; we expect you to do it. You were hired because ABCB8 you kick ass; we expect you to kick ass. ABCB8XY You were hired because you can commit to a rational deadline and meet it; ABCC12 we'll expect you to do that too. You're not someone who needs a middle manager tracking your mouse clicks If You don't care about the order of lines, the quick workaround would be to pipe the solution through a sort | uniq: cat text.txt |

Categories : String

How to write a bash function that invokes a grep command with constructed fileName parameter
This happens because Variable referencing is disabled by single quotes, which cause the "$" to be interpreted literally. For example if you do: var="test" echo "$var" # will print test echo '$var' # will print $var For more info, read this: Variable Substitution, Advanced Bash-Scripting Guide.

Categories : Bash

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?
You don't need to change the delimiter to display the right part of the string with cut. The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type : grep puddle2_1557936 | cut -d ":" -f2 Another solutions (adapt it a bit) if you want fun : Using grep : grep -oP 'puddle2_1557936:K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' /home/rogers.williams/folderz/puddle2 or still with look around regex grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' /home/rogers.williams/folderz/puddle2 or with perl : perl -lne '/p

Categories : Bash

execute user inputed Windows (or bash) commands from batch (or bash) file?
Do you need a full bash prompt? Or would something like this be enough? #!/bin/bash echo -n "Enter cmd: " read COMMAND echo ${COMMAND} | bash Also, in a script, you can just execute bash and get a full prompt in the current environment.

Categories : Bash

Is overriding std::to_string for user defined enums the proper way to provide to_string for user defined enums?
That's not "overriding" (which applies to virtual functions), and you haven't added a "specialization" (which applies to templates), you've added an overload, which adds a declaration and definition of a new function to namespace std and that's forbidden: 17.6.4.2.1 Namespace std [namespace.std] The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified. A program may add a template specialization for any standard library template to namespace std only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited. A better solution would be to overload it in your own

Categories : C++

bash grep array and output array separately
You're specifying a regex (U10|U12|U14) to grep and seeking for the count. This is why you're observing that you're getting the sum of the count of individual matches. Specify one pattern at a time: #!/bin/bash echo "Enter file to check:" read file args=("U10" "U12" "U14") for pat in ${args[@]}; do echo -ne "${pat} " ; grep detected /public/files/$file | grep -c "$pat" done You probably don't need to pass -E to grep.

Categories : Bash

How can I concat two strings with tab in bash?
Try this: echo "$c" You need to quote the variable. Moreover, since you already interpreted the escape sequence during the assignment to c, you don't need to specify -e while echoing the value.

Categories : Bash

how can I get a some values in strings in bash script
Assuming that the string is in a variable named $str, and that there are no other stars * in the string, you could use an awk filter, like this: awk -F* 'NF>1{print $2}' <<< "$str" Here we use the -F option to set the field separator to the star, and if we find a line with more than one elements (one star or more), we print the second field. output: $ echo "$str" :CONNECTING TO CPL... PROCESS CPL CONNECTED... Enter command: Enter command:*RESP:0,CPrL-E1002:RESPMSG,Invalid session ID.;* Enter command:AREE:0,CPL-E1014:RESPMSG,System internal error; Enter command: Connection closed by foreign host. $ $ awk -F* 'NF>1{print $2}' <<< "$str" RESP:0,CPrL-E1002:RESPMSG,Invalid session ID.;

Categories : Linux

delete strings from file bash
You could use sed: sed -i 's/^[0-9]{9}|MAC:[0-9A-Fa-f]{2}([-:][0-9A-Fa-f]{2}){5}//g' input.log Between the 's/ and //g' is a regular expression that matches the removal criteria in your question. The s flag in front means "search and replace" the regular expression. The // means replace the regular expression with nothing. The g flag at the end means "replace all matches" if they occur more than once in a line. Finally, the -i switch means "edit the files in-place". This solution assumes that your call IDs are all 9 digits and that the MAC address has six groups of two hexadecimal digits separated by dashes or colons.

Categories : String

Appending two arrays of strings into one [BASH]
This is probably the most inefficient way to do it, but here it is without loops: IFS=$' ' c=($(paste -d ' ' <(printf "%s " "${a[@]}") <(printf "%s " "${b[@]}"))) Of course it only works if there are no newlines in the array elements

Categories : Bash

Escaping sed strings in bash script
You have two problems. The first one is that your sed command is not doing what you're expecting. Let's fix that first. I guess you want to write the user in bold green, and the rest in default unbold. This should be better: #!/bin/bash bold="e[1m" unbold="e[0m" green="e[32m" default="e[39m" who | sed "s/^([[:alpha:]_]+)(.*)/$bold$green1$default$unbold2/" Or is it really better? you see the ugly codes instead of the nice colors. And this is your second problem. This is how we'll fix it: #!/bin/bash bold=$'e[1m' unbold=$'e[0m' green=$'e[32m' default=$'e[39m' who | sed "s/^([[:alpha:]_]+)(.*)/$bold$green1$default$unbold2/" or, if you don't like ANSI-C quotings: #!/bin/bash bold=$(echo -e "e[1m") unbold=$(echo -e "e[0m") green=$(echo -e "e[32m") default=$(echo -e "e[39m") who | sed "s/

Categories : Bash

Bash Concatenating Strings Improperly
Your file has DOS line endings; the at the end of $line causes the cursor to return to the beginning of the line, which only affects your output when $line is not the last thing being printed before the newline. You should remove them with something like dos2unix. You can use something similar to Perl's chomp command to remove a trailing carriage return, if one is present: # $' ' is bash-only, but easy to type. For POSIX shell, you'll need to find # someway of entering ASCII character 13; perhaps Control-V Control-M line=${line%$' '} Useful if, for whatever reason, you can't (or don't want to) fix the input before reading it.

Categories : Bash

Why strings are declared or defined using character pointer
String literal is a special, simple, form of writing an array aggregate: you can write "hello" instead of {'h', 'e', 'l', 'l', 'o', ''} (note the terminating zero, which is added automatically). Note that an array declaration is not only possible, but is sometimes desirable: char str[] = "hello"; str[0] = 'H'; // OK lets you modify the string, as opposed to char *str = "hello"; str[0] = 'H'; // Undefined behavior which does not allow modifications.

Categories : C

Java convention for storing all defined Strings
You can use resource bundles. Create a file called messages.properties in src or the subdirectory corresponding to the desired package and add strings to it in the following manner. No quoting is needed. ClassThatUsesAString.stringName=foo AnotherClass.stringName=bar AnotherClass.anotherString=baz You can then access these strings as follows: ResourceBundle rsrc = ResourceBundle.getBundle("messages"); and then: rsrc.getString(stringName); For example, if FooClass requires string quxString, then add to messages.properties: FooClass.quxString=waldo was here Notice lack of quotes. Now grab it with: rsrc.getString("FooClass.quxString"); This does not enforce class boundaries and naming with the class is only for convenience. If the strings are related closely, an enum may be be

Categories : Java

Using curl POST with variables defined in bash script functions
You don't need to pass the quotes enclosing the custom headers to curl. Also, your variables in the middle of the data argument should be quoted. Try this code in your script: curl -i -H "Accept: application/json" -H "Content-Type:application/json" -X POST --data '{"account":{"email":"'"$email"'","screenName":"'"$screenName"'","type":"'"$theType"'","passwordSettings":{"password":"'"$password"'","passwordConfirm":"'"$password"'"}},"firstName":"'"$firstName"'","lastName":"'"$lastName"'","middleName":"'"$middleName"'","locale":"'"$locale"'","registrationSiteId":"'"$registrationSiteId"'","receiveEmail":"'"$receiveEmail"'","dateOfBirth":"'"$dob"'","mobileNumber":"'"$mobileNumber"'","gender":"'"$gender"'","fuelActivationDate":"'"$fuelActivationDate"'","postalCode":"'"$postalCode"'","country

Categories : Json

bash: find string in multiple other strings
The simplest way, IMO, would be to just hardcode a bunch of case...esac labels. #!/bin/bash function lookup() { case "$1" in apple|banana|kiwi|melon) echo "FRUIT" ;; radish|lettuce|potato) echo "VEGETABLE" ;; blue|red|yellow|green|brown) echo "COLOR" ;; esac } MY_CHOICE="kiwi" MY_CHOICE_GROUP=$(lookup "$MY_CHOICE") echo $MY_CHOICE: $MY_CHOICE_GROUP See it live on ideone Otherwise, consider associative arrays, see it live on ideone: #!/bin/bash declare -A groups groups["apple"]="FRUIT" groups["banana"]="FRUIT" groups["kiwi"]="FRUIT" groups["melon"]="FRUIT" groups["radish"]="VEGETABLE" groups["lettuce"]="VEGETABLE" groups["potato"]="VEGETABLE" groups["blue"]="COLOR" groups

Categories : String

Bash script trouble with comparing strings
You should add spaces. Treat [[ or [ as if it's another command like test and other builtins. And like other commands, it requires a space after its name. It's also recommended that you use [[ ]] over [ ] in Bash since [[ ]] doesn't split its variables with IFS and do pathname expansions. It also has more features over the other. #!/bin/bash STR="Hello World" if [[ $STR = "Hello World" ]]; then echo "passed test" else echo "didn't pass test" fi

Categories : Bash

Comparing UTC date/time strings in Bash
Here's how I would do it: with sort. dates=( 2013-08-09T14:20:47.000Z 2013-08-09T14:31:47.000Z ) latest=$(for date in ${dates[@]} do echo $date done | sort | tail -n 1) echo $latest # outputs "2013-08-09T14:31:47.000Z" This is obviously just a sample script, modify as needed - it could easily be turned into a function like: function latest() { local dates="$@" for date in ${dates[@]} do echo $date done | sort | tail -n 1 } latest ${dates[@]} # outputs "2013-08-09T14:31:47.000Z"

Categories : Arrays

Concatenate strings in multiple lines using bash
I think your script is too complex. I don't think you need command substitution here. May you try this one seeds= for i in $*; do seeds="$seeds - $i" done; echo -e ${seeds#\n}

Categories : String

Is it better to use git grep than plain grep if we want to search in versioned source code?
git grep only searches in the tracked files in the repo. With grep you have to pass the list of files to search through and you would have filter out any untracked files yourself. So if you are searching for something that you know is in the repo, git grep saves you time as all you have to do is provide the pattern. It also is useful for not having to search through anything that is untracked in the repo.

Categories : Linux

How do I list the files having particular strings from group of directories in bash?
In fact grep itself would be fine for this. However I would strongly suggest ack-grep. It is a good alternative to grep which just suit your need. You can find it here With ack-grep it is just as simple as ack-grep --cc --cpp "(hello|how|todo)"

Categories : Linux



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