Tag Info

New answers tagged

9

GNU grep's -w will only consider the 26+26+10+1 (ASCII letters, digits and underscore) as word constituents. You can't change that, even by using a different locale (even in a locale where é is considered a letter, Stéphane would still be St and phane separated by the non-word é). You can however implement that logic by hand: grep -E ...


0

In POSIX system, you can use expr: $ a=a $ expr "$a" - 0 >/dev/null 2>&1 $ [ "$?" -lt 2 ] && echo Integer || echo Not Integer


0

You can use the -eq test on the string, with itself: $ dash -c 'a="a"; if [ "$a" -eq "$a" ] ; then echo number; else echo not a number; fi' dash: 1: [: Illegal number: a not a number $ dash -c 'a="0xa"; if [ "$a" -eq "$a" ] ; then echo number; else echo not a number; fi' dash: 1: [: Illegal number: 0xa not a number $ dash -c 'a="-1"; if [ "$a" -eq "$a" ] ; ...


5

Whether dash, bash, ksh, zsh, POSIX sh, or posh ("a reimplementation of the Bourne shell" sh) ; the case construct is the most widely available and reliable: case $1 in (*[!0-9]*|"") false ;; (*) true ;; esac


0

Perhaps with expr? if expr match "$1" '^\([0-9]\+\)$' > /dev/null; then echo "integer" else echo "non-integer" fi


0

Try using it as an arithmetic expansion, and see if it works. Actually, you need to be a bit stricter than that, because arithmetic expansions would ignore leading and trailing spaces, for instance. So do an arithmetic expansion, and make sure that the expanded result matches the original variable exactly. check_if_number() { if [ "$1" = "$((${1}))" ] ...


8

The following detect integers, positive or negative, and work under dash and are POSIX: Option 1 echo "$1" | grep -Eq '^[+-]?[0-9]+$' && echo "It's an integer" Option 2 case "${1#[+-]}" in ''|*[!0-9]*) echo "Not an integer" ;; *) echo "Integer" ;; esac Or, with a little use of the : (nop) command: ! case ${1#[+-]} in ...


2

Based on the input you show in your question, this should work: $ grep -oP '^[ @]*R.* \K.*' gitolite-info-output SecureBrowse anu-wsd entrans git-notes gitolite gitolite-admin indic_web_input proxy testing vic This is using GNU grep's -P switch to enable Perl Compatible Regular Expressions which give us \K : "Exclude anything matched up to this point". ...


2

If you want to stick with you one, use this: grep -E "^[[:alpha:]]+::[[:alpha:]]+\(\)[[:space:]]\[.*\]$" For example: $ echo "Abc::xyz() [18-Feb-15 12:09:16]" | \ grep -E "^[[:alpha:]]+::[[:alpha:]]+\(\)[[:space:]]\[.*\]$" Output: Abc::xyz() [18-Feb-15 12:09:16] This can be made simpler: grep -E "^[^:]+::[^(]+\(\) \[[^]]+\]$" Check: $ echo ...


2

Using awk: awk '{print "level="$5"\n""grid="$12"\n""boxes="$15"\n""tasks="$18}' file level=512^3 grid=16^3 boxes=32^3 tasks=800


1

If the line always has exactly this structure, read can do this in a single line with no external processes: read x x x x level x x x x x x grid x x boxes x x tasks x <<<"$line" (also using a herestring). This will save all the words you don't care about into x (to be ignored) and the values you wanted into their respective variables.


9

Bash can match regular expressions with the =~ operator in [[ ... ]]: #! /bin/bash line='attempting to create a 512^3 level (with Dirichlet BC) using a 16^3 grid of 32^3 boxes and 800 tasks...' num='([0-9^]+)' nonum='[^0-9^]+' if [[ $line =~ $num$nonum$num$nonum$num$nonum$num ]] ; then level=${BASH_REMATCH[1]} grid=${BASH_REMATCH[2]} ...


2

If this is output from a program / script you've written and the text is formulaic (i.e. follows this pattern exactly) you can just use cut. #!/bin/bash $STRING='attempting to create a 512^3 level (with Dirichlet BC) using a 16^3 grid of 32^3 boxes and 800 tasks...' level=$(echo $STRING | cut -d' ' -f5 -) grid=$(echo $STRING | cut -d' ' -f12 -) ...


1

You need to look at the character before the percent. sed 's/\([^\\]\)%.*/\1/' If the previous character is not a backslash, keep that char and remove the rest. This answer assumes that the % does not appear at the beginning of the line. If it does, then we need to check for it sed 's/\(^\|[^\\]\)%.*/\1/'


1

in perl regexp (grep -P ...) you may use \Q...\E to protect meta chars grep -P "(^|,)\Q$EMAIL\E(,|$)" file.csv where: (^|,) = start of field (,|$) = end of field


0

I solved this one for me using grep and -A option with another grep. grep first_line_word -A 1 testfile | grep second_line_word The -A 1 option prints 1 line after the found line. Of course it depends on your file and word combination. But for me it was the fastest and reliable solution.


2

You should not believe them if they tell you it cannot be done. You should believe them, however, if they tell you it's not easy. sed '\|*/|!{ s|/\*|\n&| #if ! */ repl 1st /* w/ \n/* h; s|foo|bar|g;/\n/!b #hold; repl all foo/bar; if ! \n branch G; s|\n.*\n||;:n #Get; clear difference; :new label n; ...


2

I’ve simplified your input string to qABxBCzABxBCDEFw, where A represents [ B represents - C represents ] D represents {\+ E represents the text between the +s (including the URL) F represents \+} Lower case letters represent everything else. So here are some substitute commands run against the input: Command ...


2

You have to use a negative lookaround: perl -pe 's|\[-((?!-\]).)*-\] {\+(\S+… https://t.co/.*)\+}|\2|' <<<$text The problem is the first occurence of [- matches. Then the non-greediness of the pattern doesn't take the desired effect, it doesn't matter how non-greedy it is. With a negative lookaround you can match everthing except of the string ...


3

First, there's a problem: you didn't mention encoding in your question, which makes me inclined to believe that you aren't aware of how it factors into this. Character encodings determine the meaning of individual bytes. This means we need to start with a small history lesson, and the answer to whether or not this is easy is already "no". Your example ...


1

Be aware that matching email addresses is a LOT harder that what you have. See an excerpt from the Mastering Regular Expressions book However, to answer your question, for a basic regular expression, your quantifiers need to be one of *, \+ or \{m,n\} (with the backslashes) pattern='^[a-zA-Z0-9]\+@[a-zA-Z0-9]\+\.[a-z]\{2,\}' grep "$pattern" regexfile ...


2

It is possible to enable the /g flag on :s substitutions by default by setting set gdefault in .vimrc. If this is set using :%s/PATTERN/gn will cause Vim to count occurrences of chars or words once per line and ignore all other occurrences. Either use :%s/PATTERN/n in this case or remove set gdefault from .vimrc.


0

If you execute cmd ls -a | grep ^\. then grep do not consider "\" as a special character and meaning of "." do not get escaped. When we use cmd ls -a | grep "^\." then grep considers "\" as a special character and meaning of "." gets escaped. It will give you a result as expected. If you want to use grep cmd without quotes then you should escape "\" ...


1

If your find command has the -maxdepth option (Linux (GNU or BusyBox), FreeBSD, NetBSD, OSX): find /var/www -maxdepth 3 -name wp-cron.php -exec php -q "{}" \; If you want to run wp-cron.php files at an exact depth, you can use wildcards: for x in /var/www/*/*/wp-cron.php; do php -q wp-cron.php done You can run locate wp-cron.php to quickly list ...


2

The search in less uses regular expressions. To accomplish the search you are looking for, simply replace the shell wildcard ? with .. /x 1..


18

Quote the argument to grep, thus ls -a | grep '^\.' The reason for this is that the shell handles \. and turns it back into plain ., which grep then treats as a single-character wildcard. If in doubt, always quote a string that contains (or might contain) a character that's special to the shell.


11

You need to put the grep regex inside quotes. ls -a | grep '^\.' Note: Don't parse the output of ls command.


4

In Vim, you could limit your substitution to the lines that contain NX: :g/NX/s/N1/NX/ Preceding the substitution with /NX/ makes Vim perform it only on the next line that contains NX (using ranges), and using :g makes it run on all lines that match NX.


1

You don't necessarily need to open the file in vim to do this. You can do it on the command line sed '/NX/s/N1/NX/g' <filename> >> <newfilename> and then rename the <newfilename> to the original file.


2

Another way with sed that doesn't print empty lines: sed 's/|END|/\ /g;/^$/!P;D' infile e.g. input: T|one|two|END|T|three|four|END| T|five|six|END|T|seven|eight|END| T|nine|ten|END|T|eleven|twelve|END| output: T|one|two T|three|four T|five|six T|seven|eight T|nine|ten T|eleven|twelve same thing with ed: ed -s infile <<'IN' 1,$j s/|END|/\ /g ...


1

One possibility, use cut: $ cat junk.txt linux-vdso.so.1 => (0x00007ffffc1fe000) libavfilter.so.0 => not found libpostproc.so.51 => not found libswscale.so.0 => not found libavdevice.so.52 => not found libavformat.so.52 => not found libavcodec.so.52 => not found libavutil.so.49 => not found libm.so.6 => ...


2

You have to use \s instead of \w (which match a word character) to match any single character considered whitespace, include [\t\n\f\r ]: ldd /usr/bin/ffmpeg | grep -oP "^([a-z0-9.-]|\s)*" or: ldd /usr/bin/ffmpeg | grep -oP "^\s*[a-z0-9.-]*"


4

The best solution for this is to use awk: $ ldd /usr/bin/ppdhtml | awk '/ => / { print $1 }' | head -n1 libcupsppdc.so.1 To do this using grep, you will need to use the lookahead and lookbehind features of PCRE: $ ldd /usr/bin/ppdhtml | grep -Po '(?<=\t).+(?= => )' | head -n1 libcupsppdc.so.1 The lookahead and lookbehind features affect that ...


3

Another possibly awk command and using its RS option would be: awk '$1=$1' RS="\|END\|" file Will print those records (based on awk's Record Separator) which are not empty( has at least one field) to prevent printing empty lines. Tested on this input: T|somthing|something|END|T|something2|something2|END| Test|END| |END| Gives this output: ...


5

You can use awk: $ awk -F'\\|END\\|' '{$1=$1}1' OFS='\n' file T|somthing|something T|something2|something2 -F'\\|END\\|' set field separator to |END| OFS='\n' set ouput field separator to newline $1=$1 cause awk reconstruct $0 with OFS as field separator 1 is a true value, causeawk print the whole input line


7

The following worked fine for me: $ sed 's/|END|/\ /g' foobar T|somthing|something T|something2|something2 Notice that I just put a backslash followed by the enter key.


10

Use this: sed 's/|END|/\n/g' test.txt What you attempted doesn't work because sed uses basic regular expressions, and your sed implementation has a \| operator meaning “or” (a common extension to BRE), so what you wrote replaces (empty string or END or empty string) by a newline.


4

echo $above_string | grep -oP "^([^?]*\?){2}\K[^?]*" Change 2 to the n - 1 value in order to obtain the nth string. This assumes that you want the nth string in that line. You have n - 1 strings with no ? ending with a literal '?' (\? since it's a special character in perl regex). Then with \K you state you are not interested in the previous contents, ...


3

With sed you can do: sed '/\n/P;//d;s/[^?]*/\n&\n/[num];D' ...where you would replace the [num] above with some number representing the desired occurrence. If the numbered occurrence you specify does not exist, as is demonstrated in the following example, sed will simply print nothing at all. echo ,2,3 | sed '/\n/P;//d;s/[^,]*/\n&\n/4;D' Above ...


2

sed You can use sed for this, but it is not advisable, e.g. here is a zero-based solution that uses a quantifier to select the desired field: n=1 sed 's/\([^?]*? *\)\{'$n'\}//; s/?.*//' <<<"$above_string" Output: Elvis August 16


4

Using Awk to print the second and third records separated by newlines: awk -F"?" '{printf "%s\n%s\n", $2,$3}' Elvis August 16 Leonard Nimoy February 27 If you want to swap out the record, you can set it as a variable: awk -v record=2 -F"?" '{print $record}' Elvis August 16


9

How about using cut? If you'd like to print the 2nd pattern echo "$above_string" | cut -f2 -d "?" Second column onward echo "$above_string" | cut -f2- -d "?"


1

With your regular expression you are recognizing: "RvA_X-IRB-il-CA101-RvA_X-IRB+020000-20150327212332-055582-P" in part because you are using \1 as others have pointed out. Note the repeated "RvA_X-IRB". However, it could be important to note that you are using "\b" as well, and this is going to work only when you do have a "non-word" character in one ...


1

Sed solution: sed -n ':2;/IDA:6d87de8/{p;/exception/{:1;n;/IDA:/!{p;b1};b2}}' The script suppres output (-n option), until meet appropriate IDA (/IDA:6d87de8/) which will be printed (p). Then pattern(line) will be checked for "exeption" presence and, if so, starts to operate with next line (n). If the next line do not consist IDA: the line will be printed ...


1

This prints the respective data (each preceded with the line number) to files named as the IDA: awk 'match($0,/IDA:[^ ]+/) { print NR, $0 > substr($0,RSTART+4,RLENGTH-4) }' logfile


3

Perl solution: perl -ne '$id = "6d87de8e-1276-4496-b49d-dd4cd375cbe4"; print if $match = (/IDA:$id/ .. /IDA:(?!$id)/) and $match !~ /E0$/ ' *.log Explanation: /regex1/ .. /regex2/ returns true for lines between the matches. IDA:(?!$id) meand IDA: not followed by $id. the last line in a range is denoted by the E0 suffix ...


1

Inside comments (/* .*? */) remove everything except newlines; grep non empty lines: perl -p0E 's!(/\*.*?\*/)!$1 =~ s/.//gr!egs;' test.js |grep -nP '\S' which outputs: 9:(function(a,b){function d(b) {return!a(b).parents().andSelf().filter(f 17:(function(a,b){if(a.cleanData){var c=a.cleanData;a.cleanData=function(b


0

Using Awk: awk '/^*\/\(/ {gsub(/\*\/|\/\*!/,""); print NR":",$0}' js 9: (function(a,b){function d(b) {return!a(b).parents().andSelf().filter(f 17: (function(a,b){if(a.cleanData){var c=a.cleanData;a.cleanData=function(b


0

One approach not covered by terdon's comprehensive answer is Bash's parameter expansion (which requires no additional process): vers=$(uname -r) && printf "%s\n" "${vers%%-*}" 3.14.37 vers="-jwl35" && printf "%s\n" "${vers#*-}" jwl35


0

Depending on what you wish to match awk -F"[][]" '/postfix|spamd/{print $2}' maillog



Top 50 recent answers are included