integer-only wildcards in grep - bash

i have command that outputs a collection strings that look like this:
json.formats[0]].url = "https://example.com/ar.html"
json.formats[1].url = "https://example.com/es.html"
json.formats[2s].url = "https://example.com/ru.html"
json.formats[3].url = "https://example.com/pt.html"
json.formats[73].url = "https://example.com/ko.html"
json.formats[1502].url = "https://example.com/pl.html"
(there are many more instances, however for simpilcity's sake theyve been removed)
i can use the command below
myCmd | grep -e 'json\.formats\[.*\]\.url\ \=\ '
however i only want the wildcard to match integers, and to throw out non-integer matches. it gives me the following:
json.formats[0]].url = "https://example.com/ar.html"
json.formats[1].url = "https://example.com/es.html"
json.formats[2s].url = "https://example.com/ru.html"
json.formats[3].url = "https://example.com/pt.html"
json.formats[73].url = "https://example.com/ko.html"
json.formats[1502].url = "https://example.com/pl.html"
what i really want is this:
json.formats[1].url = "https://example.com/es.html"
json.formats[3].url = "https://example.com/pt.html"
json.formats[73].url = "https://example.com/ko.html"
json.formats[1502].url = "https://example.com/pl.html"
Thanks :-)

You may use:
myCmd | grep -E 'json\.formats\[[[:digit:]]+\]\.url = '
or:
myCmd | grep -E 'json\.formats\[[0-9]+\]\.url = '
[[:digit:]] is equivalent of [0-9] for most of the locales.

Related

How to check if process is already running by name in JXA

Using /usr/bin/osascript JS to automate my task, struggling with a check if process is already running or not:
const app = Application.currentApplication()
app.includeStandardAdditions = true
function run(args) {
const query = args[0]
let response = 'Wrong command passed'
if (query === 'on') { // need to check if process named "asdf" is already running
response = 'Process turned ON'
} else if (query === 'off') { // need to check if process named "asdf" is already running
response = 'Process turned OFF'
}
return response
}
JXA documentation could be better, i want to implement a check in an if construction. I've tried to make it using:
const se = Application('System Events')
const process = se.processes.byName('processname')
But it has no effect.
Solved myself:
const PNAME = `ps aux | grep processname | grep -v grep | wc -l | xargs echo`
Getting "processname", if it's running, it returns 1, otherwise 0.
Were I to call out to a shell to do this, I would aim to make it as an efficient combination of commands as possible. xargs, wc, and the second pipe into grep are all unnecessary: if grep processname matches, the exit status of the command will be 0, and in all other cases, non-zero. It looks like the only reason you pipe through to those other programs is because you didn't utilise the most effective set of program options when calling ps:
const PNAME = 'ps -Acxo comm | grep processname > /dev/null; echo $(( 1 - $? ))'
Even this use of grep is unnecessary, as bash can pattern match for you:
const PNAME = '[[ "$( ps -Acxo comm )" =~ processname ]]; echo $(( 1 - $? ))'
But, putting that to one side, I wouldn't get a shell script to do this unless I were writing a shell script. JXA is very capable of enumerating processes:
sys = Application('com.apple.SystemEvents');
sys.processes.name();
Then, to determine whether a specific named process, e.g. TextEdit, is running:
sys.processes['TextEdit'].exists();
which will return true or false accordingly.
Solved myself:
const PNAME = `ps aux | grep processname | grep -v grep | wc -l | xargs echo`
Getting processname, if it's running, it returns 1, otherwise 0. All what's left to do is:
if (app.doShellScript(PNAME) < 1) {
// do something
} else {
// do something else
}

Jenkins pipeline I need to execute the shell command and the result is the value of def variable. What shall I do? Thank you

Jenkins pipeline I need to execute the shell command and the result is the value of def variable.
What shall I do? Thank you
def projectFlag = sh("`kubectl get deployment -n ${namespace}| grep ${project} | wc -l`")
//
if ( "${projectFlag}" == 1 ) {
def projectCI = sh("`kubectl get deployment ${project} -n ${namespace} -o jsonpath={..image}`")
echo "$projectCI"
} else if ( "$projectCI" == "${imageTag}" ) {
sh("kubectl delete deploy ${project} -n ${namespaces}")
def redeployFlag = '1'
echo "$redeployFlag"
if ( "$projectCI" != "${imageTag}" ){
sh("kubectl set image deployment/${project} ${appName}=${imageTag} -n ${namespaces}")
}
else {
def redeployFlag = '2'
}
I believe you're asking how to save the result of a shell command to a variable for later use?
The way to do this is to use some optional parameters available on the shell step interface. See https://jenkins.io/doc/pipeline/steps/workflow-durable-task-step/#sh-shell-script for the documentation
def projectFlag = sh(returnStdout: true,
script: "`kubectl get deployment -n ${namespace}| grep ${project} | wc -l`"
).trim()
Essentially set returnStdout to true. The .trim() is critical for ensuring you don't pickup a \n newline character which will ruin your evaluation logic.

Search for strings from array in text file

I want to search a textfile for more than one string. If i find at least 1 string ( i repeat , i only need one string to be found, not all of them ) i want the program to stop and create a file in which i will find the text : "found"
This is my code that doesn't work properly :
$f = 'C:\users\datboi\desktop\dump.dmp'
$text = 'found'
$array = "_command",".command","-
command","!command","+command","^command",":command","]command","[command","#command","*command","$command","&command","#command","%command","=command","/command","\command","command!","command#","command#","command$","command%","command^","command&","command*","command-","command+","command=","command\","command/","command_","command.","command:"
$len = 9
$offset = 8
$data = [IO.File]::ReadAllBytes($f)
for ($i=0; $i -lt $data.Count - $offset; $i++) {
$slice = $data[$i..($i+$offset)]
$sloc = [char[]]$slice
if ($array.Contains($sloc)){
$text > 'command.log'
break
}
}
When i say it doesn t work properly i mean : it runs, no errors, but even if the file contains at least one of the strings from the array, it doesn't create the file i want .
This is literally what the Select-String cmdlet was created for. You can use a Regular Expression to simplify your search. For the RegEx I would use:
[_\.-!\+\^:]\[\#\*\$&#%=/\\]command|command[_\.-!\+\^:\#\*\$&#%=/\\]
That comes down to any of the characters in the [] brackets followed by the word 'command', or the word 'command' followed by any of the characters in the [] brackets. Then just pipe that to a ForEach-Object loop that outputs to your file and breaks.
Select-String -Path $f -Pattern '[_\.-!\+\^:]\[\#\*\$&#%=/\\]command|command[_\.-!\+\^:\#\*\$&#%=/\\]' | ForEach{
$text > 'command.log'
break
}
First, I would recommend using a regular expression as you can greatly shorten your code.
Second, PowerShell is good at pattern matching.
Example:
$symbolList = '_\-:!\.\[\]#\*\/\\&#%\^\+=\$'
$pattern = '([{0}]command)|(command[{0}])' -f $symbolList
$found = Select-String $pattern "inputfile.txt" -Quiet
$found
The $symbolList variable is a regular expression pattern containing a list of characters you want to find either before or after the word "command" in your search string.
The $pattern variable uses $symbolList to create the pattern.
The $found variable will be $true if the pattern is found in the file.

How to print a character using Shell script

Below is my script that acquire the MAC of the machine and store within a config file.
My problem is that within each line have the character " " and it dont print it inside the file, how can I write the file using " "
MAC=$(ifconfig eth0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}')
echo "
view.sslVerificationMode = *3*
view.autoConnectDesktop = *TRUE*
view.autoConnectBroker = *TRUE*
view.kioskLogin = *TRUE*
view.nonInteractive = *TRUE*
view.fullScreen = *TRUE*
view.nomenubar = *TRUE*
view.defaultBroker = *viewcs*
view.defaultUser = *CM-${MAC//:/_}*
" > /etc/vmware/view-mandatory-config;
sed -i 's/*/"/g' /etc/vmware/view-mandatory-config
with cat and a here-doc you can use multi-line input without escaping charaters
MAC=$(ifconfig eth0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}')
cat << EOT > /etc/vmware/view-mandatory-config
view.sslVerificationMode = "3"
view.autoConnectDesktop = "TRUE"
view.autoConnectBroker = "TRUE"
view.kioskLogin = "TRUE"
view.nonInteractive = "TRUE"
view.fullScreen = "TRUE"
view.nomenubar = "TRUE"
view.defaultBroker = "viewcs"
view.defaultUser = "CM-${MAC//:/_}"
EOT
cat will relay the stdin input generated by the here document to stdout, thus enabling redirection to a file
Simply escape double-quotes within the outer double-quotes by putting a backslash in front of them:
MAC=$(ifconfig eth0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}')
echo "
view.sslVerificationMode = \"3\"
view.autoConnectDesktop = \"TRUE\"
view.autoConnectBroker = \"TRUE\"
view.kioskLogin = \"TRUE\"
view.nonInteractive = \"TRUE\"
view.fullScreen = \"TRUE\"
view.nomenubar = \"TRUE\"
view.defaultBroker = \"viewcs\"
view.defaultUser = \"CM-${MAC//:/_}\"
" > /etc/vmware/view-mandatory-config

Converting a code from bash to php

I currently have an existing code in bash that greps a keyword from a config file:
[USER1]
usrcid = 5654654654
usrsid = XDFDFSAS22
usrmid = COMPANYNAME1
usrsrt = secret1
urlenc = http://www.url1.com
[USER2]
usrcid = 5654654667
usrsid = XDFDFSAS45
usrmid = COMPANYNAME2
usrsrt = secret2
urlenc = http://www.url2.com
I store it as a variable and use it for processing the rest of the script. What I want to achieve is to convert the behavior from bash to php and do a curl:
F1=/etc/config/file.txt
CID=`grep "\[USER1\]" -A 5 $F1 | grep usrcid | awk {'print$3'}`
SID=`grep "\[USER1\]" -A 5 $F1 | grep usrsid | awk {'print$3'}`
MID=`grep "\[USER1\]" -A 5 $F1 | grep usrmid | awk {'print$3'}`
SRT=`grep "\[USER1\]" -A 5 $F1 | grep usrsrt | awk {'print$3'}`
URI=`grep "\[USER1\]" -A 5 $F1 | grep urlenc | awk {'print$3'}`
echo $CID $SID $MID $SRT $URI
I'm really not a php guru so please excuse the code below but from a general perspective, the below code is my understanding of what I want to achieve:
<?php
include "/etc/config/file.txt"
// *** the equivalent code grep? ***
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
// *** i'm not sure if this one is correct? ***
$returned_content = get_data('$URI/cid=$CID&sid=$SID&mid=$MID&srt=$SRT')
echo $returned_content;
?>
This is my first time to ask in stackoverflow so I would like to thank you in advance!
Include doesn't do what you think it's doing. It won't get the variables you set in the text-file. If it were PHP code in the file you included, it would evaluate that, but in this case, it's only text. See the Manual
What you need is to use the parse_ini_file() function. It takes the config file as first argument, and a boolean flag as the second. The second argument is used to let the function know that you should use sections in your config file, which you do.
Example:
file.txt:
[USER1]
usrcid = 5654654654
usrsid = XDFDFSAS22
usrmid = COMPANYNAME1
usrsrt = secret1
urlenc = http://www.url1.com
[USER2]
usrcid = 5654654667
usrsid = XDFDFSAS45
usrmid = COMPANYNAME2
usrsrt = secret2
urlenc = http://www.url2.com
test.php:
<?php
$config = parse_ini_file("file.txt", true);
print_r($config);
?>
(See the manual for parse_ini_file())
This will load the config file to the $config variable, and it will contain the following:
Array
(
[USER1] => Array
(
[usrcid] => 5654654654
[usrsid] => XDFDFSAS22
[usrmid] => COMPANYNAME1
[usrsrt] => secret1
[urlenc] => http://www.url1.com
)
[USER2] => Array
(
[usrcid] => 5654654667
[usrsid] => XDFDFSAS45
[usrmid] => COMPANYNAME2
[usrsrt] => secret2
[urlenc] => http://www.url2.com
)
)
Now, to construct an URL you could use:
$url = "{$config['USER1']['urlenc']}/cid={$config['USER1']['usrcid']}&sid={$config['USER1']['usrsid']}&mid={$config['USER1']['usrmid']}&srt={$config['USER1']['usrsrt']}";
Or construct a dynamic way of iterating through the array given in the $config variable, to account for several sections. This URL you can run through the cURL function you got.

Resources