hi i am trying to concatenate three integer value in UNIX OS(SunOS 5.10). But it is not working for me .
Below is the code
a=2016
b=11
c=21
result="$a$b$c"
echo "$result"
OUTPUT-:
2016
11
21
Can anyone help???
browserDate="2016-11-21"
dateConversion="${browserDate//'-'}
echo "$date Conversion"
You need tho use printf instead of echo:
a=2016
b=11
c=21
result="$a\n$b\n$c"
printf $result
Related
i am new to unix shell scripting
I need to write a shell script that should increment a variable value (numeric) and when i run the script next time the variable should take the incremented value and it should increment once agian
any help in this would be really thankful
thanks
Try the following code:
vale=`expr 0000000000 + 1`
ed -s $0 <<EOT
1s/ ........../`printf ' %010d' $vale`/
w
q
EOT
echo $vale
You need for the value of the variable to persist somehow. One way is to save it to a file.
outputfile="~/variable.txt"
value=`cat $outputFile`
newValue=`expr $value + 1`
echo $newValue > $outputFile
I have string in this format (PUNC on one line
and i need to brake it into two separate lines as follows:
(
PUNC
how to do that?
You can do:
s='(PUNC'
r="${s/\(/(\n}"
echo -e "$r"
(
PUNC
try this:
echo "(\
PUNC"
the "\" as last character on the line signals, that the next line belongs to this line.
echo is an example here. show your code, than I can adapt the answer.
i'm confused about the $symbol for unix.
according to the definition, it states that it is the value stored by the variable following it. i'm not following the definition - could you please give me an example of how it is being used?
thanks
You define a variable like this:
greeting=hello
export name=luc
and use like this:
echo $greeting $name
If you use export that means the variable will be visible to subshells.
EDIT: If you want to assign a string containing spaces, you have to quote it either using double quotes (") or single quotes ('). Variables inside double quotes will be expanded whereas in single quotes they won't:
axel#loro:~$ name=luc
axel#loro:~$ echo "hello $name"
hello luc
axel#loro:~$ echo 'hello $name'
hello $name
In case of shell sctipts. When you assign a value to a variable you does not need to use $ simbol. Only if you want to acces the value of that variable.
Examples:
VARIABLE=100000;
echo "$VARIABLE";
othervariable=$VARIABLE+10;
echo $othervariable;
The other thing: if you use assignment , does not leave spaces before and after the = simbol.
Here is a good bash tutorial:
http://linuxconfig.org/Bash_scripting_Tutorial
mynameis.sh:
#!/bin/sh
finger | grep "`whoami` " | tail -n 1 | awk '{FS="\t";print $2,$3;}'
finger: prints all logged in user example result:
login Name Tty Idle Login Time Office Office Phone
xuser Forname Nickname tty7 3:18 Mar 9 07:23 (:0)
...
grep: filter lines what containing the given string (in this example we need to filter xuser if our loginname is xuser)
http://www.gnu.org/software/grep/manual/grep.html
whoami: prints my loginname
http://linux.about.com/library/cmd/blcmdl1_whoami.htm
tail -n 1 : shows only the last line of results
http://unixhelp.ed.ac.uk/CGI/man-cgi?tail
the awk script: prints the second and third column of the result: Forname, Nickname
http://www.staff.science.uu.nl/~oostr102/docs/nawk/nawk_toc.html
This question already has answers here:
How can I repeat a character in Bash?
(36 answers)
Closed 8 years ago.
I need to generate a string of dots (.characters) as a variable.
I.e., in my Bash script, for input 15 I need to generate this string of length 15: ...............
I need to do so variably. I tried using this as a base (from Unix.com):
for i in {1..100};do printf "%s" "#";done;printf "\n"
But how do I get the 100 to be a variable?
You can get as many NULL bytes as you want from /dev/zero. You can then turn these into other characters. The following prints 16 lowercase a's
head -c 16 < /dev/zero | tr '\0' '\141'
len=100 ch='#'
printf '%*s' "$len" | tr ' ' "$ch"
Easiest and shortest way without a loop
VAR=15
Prints as many dots as VAR says (change the first dot to any other character if you like):
printf '.%.0s' {1..$VAR}
Saves the dotted line in a variable to be used later:
line=`printf '.%.0s' {1..$VAR}`
echo "Sign here $line"
-Blatantly stolen from dogbane's answer https://stackoverflow.com/a/5349842/3319298
Edit: Since I have now switched to fish shell, here is a function defined in config.fish that does this with convenience in that shell:
function line -a char -a length
printf '%*s\n' $length "" | tr ' ' $char
end
Usage: line = 8 produces ========, line \" 8 produces """""""".
On most systems, you could get away with a simple
N=100
myvar=`perl -e "print '.' x $N;"`
I demonstrated a way to accomplish this task with a single command in another question, assuming it's a fixed number of characters to be produced.
I added an addendum to the end about producing a variable number of repeated characters, which is what you asked for, so my previous answer is relevant here:
https://stackoverflow.com/a/17030976/2284005
I provided a full explanation of how it works there. Here I'll just add the code to accomplish what you're asking for:
n=20 # This the number of characters you want to produce
variable=$(printf "%0.s." $(seq 1 $n)) # Fill $variable with $n periods
echo $variable # Output content of $variable to terminal
Outputs:
....................
You can use C-style for loops in Bash:
num=100
string=$(for ((i=1; i<=$num; i++));do printf "%s" "#";done;printf "\n")
Or without a loop, using printf without using any externals such as sed or tr:
num=100
printf -v string "%*s" $num ' ' '' $'\n'
string=${string// /#}
The solution without loops:
N=100
myvar=`seq 1 $N | sed 's/.*/./' | tr -d '\n'`
num=100
myvar=$(jot -b . -s '' $num)
echo $myvar
When I have to create a string that contains $x repetitions of a known character with $x below a constant value, I use this idiom:
base='....................'
# 0 <= $x <= ${#base}
x=5
expr "x$base" : "x\(.\{$x\}\)" # Will output '\n' too
Output:
.....
I can format the Get-Date cmdlet no problem like this:
$date = Get-Date -format "yyyyMMdd"
But once I've got a date in a variable, how do I format it? The statement below
$dateStr = $date -format "yyyMMdd"
returns this error:
"You must provide a value expression
on the right-hand side of the '-f'
operator"
The same as you would in .NET:
$DateStr = $Date.ToString("yyyyMMdd")
Or:
$DateStr = '{0:yyyyMMdd}' -f $Date
A simple and nice way is:
$time = (Get-Date).ToString("yyyy:MM:dd")
The question is answered, but there is some more information missing:
Variable vs. Cmdlet
You have a value in the $Date variable and the -f operator does work in this form: 'format string' -f values. If you call Get-Date -format "yyyyMMdd" you call a cmdlet with some parameters. The value "yyyyMMdd" is the value for parameter Format (try help Get-Date -param Format).
-f operator
There are plenty of format strings. Look at least at part1 and part2. She uses string.Format('format string', values'). Think of it as 'format-string' -f values, because the -f operator works very similarly as string.Format method (although there are some differences (for more information look at question at Stack Overflow: How exactly does the RHS of PowerShell's -f operator work?).
A very convenient -- but probably not all too efficient -- solution is to use the member function GetDateTimeFormats(),
$d = Get-Date
$d.GetDateTimeFormats()
This outputs a large string-array of formatting styles for the date-value. You can then pick one of the elements of the array via the []-operator, e.g.,
PS C:\> $d.GetDateTimeFormats()[12]
Dienstag, 29. November 2016 19.14
One thing you could do is:
$date.ToString("yyyyMMdd")
Do this if you absolutely need to use the -Format option:
$dateStr = Get-Date $date -Format "yyyMMdd"
However
$dateStr = $date.toString('yyyMMdd')
is probably more efficient.. :)
Very informative answer from #stej, but here is a short answer:
Among other options, you have 3 simple options to format [System.DateTime] stored in a variable:
Pass the variable to the Get-Date cmdlet:
Get-Date -Format "HH:mm" $date
Use toString() method:
$date.ToString("HH:mm")
Use Composite formatting:
"{0:HH:mm}" -f $date
For anyone trying to format the current date for use in an HTTP header use the "r" format (short for RFC1123) but beware the caveat...
PS C:\Users\Me> (get-date).toString("r")
Thu, 16 May 2019 09:20:13 GMT
PS C:\Users\Me> get-date -format r
Thu, 16 May 2019 09:21:01 GMT
PS C:\Users\Me> (get-date).ToUniversalTime().toString("r")
Thu, 16 May 2019 16:21:37 GMT
I.e. Don't forget to use "ToUniversalTime()"
If you got here to use this in cmd.exe (in a batch file):
powershell -Command (Get-Date).ToString('yyyy-MM-dd')
I needed the time and a slight variation on format. This works great for my purposes:
$((get-date).ToLocalTime()).ToString("yyyy-MM-dd HHmmss")
2019-08-16 215757
According to #mklement0 in comments, this should yield the same result:
(get-date).ToString("yyyy-MM-dd HHmmss")
Format Date Time to your Output Needs
If you want to format the date and assign the string to a variable.
I have combined both PowerShell and .NET to provide the flexibility.
$oDate = '{0}' -f ([system.string]::format('{0:yyyyMMddHHmmss}',(Get-Date)))
How this Works
PowerShell Operator - '{0}' -f (.....)
.NET Notation - [system.string]::format('customformat',InputObject)
Customised Format by combining PowerShell with .NET - '{0:yyyyMMddHHmmss}'
Input Object provided by PowerShell cmdlet - (Get-Date)
Stored in the PowerShell variable - $oDate
Example
If the date and time when run was Monday, 5 July 2021 5:45:22 PM (Format '{0:F}').
$oDate = 20210705174522
Using the Code
You can customise the the string to meet your requirements by modifying 'yyyMMddHHmmss' using the Microsoft .NET Custom Date Time Notation.
You could just use this to select the format you want and then past it wherever it is needed.
$DTFormats = (Get-Date).GetDateTimeFormats()
$Formats = #()
$i=0
While ($i -lt $DTFormats.Count){
$row = [PSCustomObject]#{
'IndexNumber' = $i
'DateTime Format' = $DTFormats[$i]
}
$Formats += $row
$i++
}
$DTSelection = ($Formats | Out-GridView -OutputMode Single -Title 'Select DateTime Format').IndexNumber
$MyDTFormat = "(Get-Date).GetDateTimeFormats()[$DTSelection]"
Write-Host " "
Write-Host " Use the following code snippet to get the DateTime format you selected:"
Write-Host " $MyDTFormat" -ForegroundColor Green
Write-Host " "
$MyDTFormat | Clip
Write-Host " The code snippet has been copied to your clipboard. Paste snippet where needed."
I converted my dueDate string to a datetime then formatted it.
[Datetime]::ParseExact($dueDate,'MM/dd/yyyy H:mm:ss',$null).ToString('MM/dd/yyyy')