Replace javascript code between two patterns using bash - bash

I have the following code:
this.directives.forEach(function (dir) {
var myVar = "hello";
if (control.text !== myVar) {
cleanUp(control);
if (dir)
setUpControl(myVar, dir);
control = dir;
}
});
And need to replace everything that is between: if (control !== myVar) { and }. I have followed this answer and tried the following:
sed -i 's/(if \(control\.text !== myVar\) \{).*?(\})/\1 REPLACEMENT_STRING \2/is' myFile.js
which returns
sed: 1: "s/(if \(control\.text ! ...": RE error: invalid repetition count(s)

You can try this one but it's not really efficient if some '{' appear in your function...
sed '/if (control\.text !== myVar) {/!b;p;s/.*/REPLACEMENT_STRING/p;:A;N;/}/!{s/.*//;bA};D' myFile.js

Related

How to print a value in single line using shell command?

I have written a shell script in a groovy function which should return the the output (in a single line) as abcd-def-chart but, I am getting the output as shown below in 2 different lines:
abcd-def
-chart
My groovy code:
String getChartName(Map configuration = [:]) {
if (configuration.chartName != null) {
return configuration.chartName
}
chartName = ""
if (configuration.buildSystem == 'maven') {
chartName = getMavenProjectName() + "-chart"
}
echo "chartName: ${chartName}"
return chartName
}
String getMavenProjectName() {
echo "inside getMavenProjectName +++++++"
def mavenChartName = sh returnStdout:true, script: '''
#!/bin/bash
GIT_LOG=$(env -i git config --get remote.origin.url)
basename "$GIT_LOG" .git; '''
echo "mavenChartName: ${mavenChartName}"
return mavenChartName
}

replace string in class bash and azuredevops (ios xamarin pipeline)

I am trying to write a bash script to change a string in a class for my azure devops pipeline.But cannot make it work.
Copied the script from
https://github.com/Microsoft/appcenter-build-scripts-examples/blob/master/xamarin/app-constants/appcenter-pre-build.sh
my bash attempt:
Added a bash task (inline script)
Created an env variable API_URL with value ="https://production.com/api"
My Class to change
namespace Core
{
public class AppConstant
{
public const string ApiUrl = "https://production.com/api";
public const string AnotherOne="AAA";
}
}
My script
if [ ! -n "$API_URL" ]
then
echo "You need define the API_URL variable"
exit
fi
APP_CONSTANT_FILE=$(Build.SourcesDirectory)/MyProject/Core/AppConstant.cs
if [ -e "$APP_CONSTANT_FILE" ]
then
echo "Updating ApiUrl to $API_URL in AppConstant.cs"
sed -i '' 's#ApiUrl = "[a-z:./]*"#ApiUrl = "'$API_URL'"#' $APP_CONSTANT_FILE
echo "File content:"
cat $APP_CONSTANT_FILE
fi
why does my variable not change? many thanks
Your script is correct and will get desired output, only remove the dual apostrophes after sed -i:
sed -i 's#ApiUrl = "[a-z:./]*"#ApiUrl = "'$API_URL'"#' $APP_CONSTANT_FILE
However I would also change regexp at least to this, since . (dot) is reserved as any character in regexp:
sed -i 's#ApiUrl = "[a-z:\./]*"#ApiUrl = "'$API_URL'"#' $APP_CONSTANT_FILE
Or even to this (in order to take whatever characters between quotes):
sed -i 's#ApiUrl = "[^"]*"#ApiUrl = "'$API_URL'"#' $APP_CONSTANT_FILE
Test:
$ cat > developer9969.txt
namespace Core
{
public class AppConstant
{
public const string ApiUrl = "https://production.com/api";
}
}
API_URL='https://kubator.com/'
APP_CONSTANT_FILE='./developer9969.txt'
sed -i 's#ApiUrl = "[^"]*"#ApiUrl = "'$API_URL'"#' $APP_CONSTANT_FILE
$ cat $APP_CONSTANT_FILE
namespace Core
{
public class AppConstant
{
public const string ApiUrl = "https://kubator.com/";
}
}

Expanding string variables in bash to toggle a value in JSON

I am trying to create a bash function where I can switch environments, below is what I tried. I installed the npm json package globally to edit the relevant file inline, but that may not be needed.
devUrl () { 'https://some-url.com'; }
testUrl () { 'https://some-test-url.com'; }
switchEnv () { 'json -I -f config.json -e "this.url = (this.url == "$1" ? "$2" : "$1")"'; }
alias switch='switchEnv devUrl testUrl';
what am I missing/doing wrong?
I also tried to template the strings devUrl and testUrl inside the double quotes in the switchEnv function, but that's where I got stuck.
Update:
I tried this:
devUrl='https://some-url.com'
testUrl='https://some-test-url.com'
switchEnv() { json -I -f config.json -e "this.url = (this.url == "$devUrl" ? "$testUrl" : "$devUrl")"; }
but got the following error:
this.url = (this.url == https://some-url.com ? https://some-test-url.com : https://some-url.com)
^
SyntaxError: Unexpected token :
at new Function (<anonymous>)
at main (/usr/local/lib/node_modules/json/lib/json.js:1289:27)
it doesn't like the : after https for some reason.
The below is a sample implementation that does what you're looking for; see the notes below for some details on why it was implemented as it was.
# String assignments
devUrl='https://some-url.com'
testUrl='https://some-test-url.com'
configFile="$PWD/config.json"
# Functions
switchEnv() {
local tempfile
tempfile=$(mktemp "$configFile.XXXXXX")
if jq --arg a "$1" \
--arg b "$2" \
'if .url == $a then .url=$b else .url=$a end' <"$configFile" >"$tempfile"; then
mv -- "$tempfile" "$configFile"
else
rm -f -- "$tempfile"
return 1
fi
}
switch() { switchEnv "$devUrl" "$testUrl"; }
Notes:
Unlike aliases, function bodies should be actual code, not strings containing code.
Storing data (as opposed to code) should be done using variables (be they strings or arrays, as appropriate).
Passing data out-of-band from code allows a malicious value of devUrl or testUrl to escape its quoting and run arbitrary json or jq commands. This is wise, in no small part because these languages become more powerful over time: Old versions of jq had no operations that wouldn't run in constant-time, whereas modern versions of the language allow code to be expressed that can be used for denial-of-service attacks; future versions might also add I/O support, allowing malicious code to have a wider array of surprising behaviors.
Now, let's say you were going to ignore the warning (above) about the importance of separating data and code. How would we modify your current code to behave "correctly" (when the strings being handled are non-malicious)?
switchEnv() {
json -I -f config.json -e 'this.url = (this.url == "'"$devUrl"'" ? "'"$testUrl"'" : "'"$devUrl"'")'; }
}

Suppressing system command called from awk script

I am currently running this script in Windows 7.
So, I have a program that is meant to color-code output from another command (mkmk) and tally up varying numbers of errors and other notable stats, etc. So right now, it starts as a batch file which
Turns off echo
Sets some color values to variables
Calls the mkmk command and the awk script together
The awk script then parses line by line, and calls a function which then calls an exe that performs the Colorizing. Works like follows:
/: error/ {
CntError++ ;
TraError[CntError] = $0;
colorf(cErrorDcb,$0) ;
next
}
function colorf(fg, str ) {
if ( Couleur < 1 )
{
printf("%s\n",str);
}
else
{
if ( System == "UNIX" )
{
printf("%s%s%s%s\n",fg,bg,str,NORMAL);
}
else
{
system("Colorize.exe /c:" fg " \"" str "\"");
printf("\n");
}
}
}
So, everything works, EXCEPT that every time system("Colorize.exe") is called (a lot), the command is outputted in the terminal and clutters up the output. It doesn't appear to be affected by the #echo off command in my batch file since it is called inside the awk script. Is there anyway to hide only these system commands but keep the rest of my awk output?
I have no idea what the magical Windows incantations are to control what displays on the terminal but in general instead of calling system() and letting the command it calls produce it's own output that's getting mixed in with the awk output, use getline to read the result of the call to populate a variable and then print that from awk. Something like this:
/: error/ {
TraError[++CntError] = $0
print colorf(cErrorDcb,$0)
next
}
function colorf(fg, str, cmd, line, colorStr) {
if ( Couleur < 1 ) {
colorStr = str
}
else if ( System == "UNIX" ) {
colorStr = fg bg str NORMAL
}
else {
cmd = "Colorize.exe /c:" fg " \"" str "\""
colorStr = ( (cmd | getline line) > 0 ? line : str )
close(cmd)
}
return colorStr
}
I got rid of all of the useless semi-colons too.
Best advice - get cygwin!

Warning: implode() [<a href='function.implode'>function.implode</a>]: Invalid arguments passed in C:\wamp\www\test.php on line 71

i try to convert csv file to tsv using below code.
in my csv the first word has no value.
when i run the code it generate tsv file correctly , but it gives above error. please help
Thanks
$myfile = "file path";
function convert($filename)
{
if(#$fh_in = fopen("{$filename}.csv","r"))
{
$fh_out = fopen("{$filename}.tsv","a");
while(!feof($fh_in))
{
$line = array();
$line = fgetcsv($fh_in,1024);
fwrite($fh_out,implode("\t",$line)."\n");
}
fclose($fh_in);
fclose($fh_out);
}
else {
echo "File doesn’t exist\n";
return false;
}
echo "Conversion completed!\n";
return true;
}
convert($myfile);
According to PHP Manual, implode can be
string implode ( string $glue , array $pieces )
string implode ( array $pieces )
So in your case if $line is empty then it will execute with second prototype and consider \n as $pieces which is wrong. So check for value in $line before calling implode

Resources