date
int64
1,220B
1,719B
question_description
stringlengths
28
29.9k
accepted_answer
stringlengths
12
26.4k
question_title
stringlengths
14
159
1,327,107,993,000
I want to assign the result of an expression (i.e., the output from a command) to a variable and then manipulate it – for example, concatenate it with a string, then echo it.  Here's what I've got: #!/bin/bash cd ~/Desktop; thefile= ls -t -U | grep -m 1 "Screen Shot"; echo "Most recent screenshot is: "$thefile; But t...
A shell assignment is a single word, with no space after the equal sign. So what you wrote assigns an empty value to thefile; furthermore, since the assignment is grouped with a command, it makes thefile an environment variable and the assignment is local to that particular command, i.e. only the call to ls sees the a...
How can I assign the output of a command to a shell variable?
1,327,107,993,000
Is there an easy way to substitute/evaluate environment variables in a file? Like let's say I have a file config.xml that contains: <property> <name>instanceId</name> <value>$INSTANCE_ID</value> </property> <property> <name>rootPath</name> <value>/services/$SERVICE_NAME</value> </property> ...etc. I w...
You could use envsubst (part of gnu gettext): envsubst < infile will replace the environment variables in your file with their corresponding value. The variable names must consist solely of alphanumeric or underscore ASCII characters, not start with a digit and be nonempty; otherwise such a variable reference is igno...
Replace environment variables in a file with their actual values?
1,327,107,993,000
If there's a "First World Problems" for scripting, this would be it. I have the following code in a script I'm updating: if [ $diffLines -eq 1 ]; then dateLastChanged=$(stat --format '%y' /.bbdata | awk '{print $1" "$2}' | sed 's/\.[0-9]*//g') mailx -r "Systems and Operations <sysadmin@[redacted].edu...
You can change the here-doc operator to <<-.  You can then indent both the here-doc and the delimiter with tabs: #! /bin/bash cat <<-EOF indented EOF echo Done Note that you must use tabs, not spaces, to indent both the here-doc and the delimiter. This means the above example won't work copied (Stack Exchange...
Can't indent heredoc to match code block's indentation
1,327,107,993,000
I have the grep command. I'm searching for a keyword from a file, but I don't want to display the match. I just want to know the exit status of the grep.
Any POSIX compliant version of grep has the switch -q for quiet: -q Quiet. Nothing shall be written to the standard output, regardless of matching lines. Exit with zero status if an input line is selected. In GNU grep (and possibly others) you can use long-option synonyms as well: -q, --quiet, --silent ...
How can I suppress output from grep, so that it only returns the exit status?
1,445,607,289,000
I'm trying to copy a batch of files with scp but it is very slow. This is an example with 10 files: $ time scp cap_* user@host:~/dir cap_20151023T113018_704979707.png 100% 413KB 413.2KB/s 00:00 cap_20151023T113019_999990226.png 100% 413KB 412.6KB/s 00:00 cap_20151023T113020_649251955.png 100% 4...
@wurtel's comment is probably correct: there's a lot of overhead establishing each connection. If you can fix that you'll get faster transfers (and if you can't, just use @roaima's rsync workaround). I did an experiment transferring similar-sized files (head -c 417K /dev/urandom > foo.1 and made some copies of that fi...
Why is scp so slow and how to make it faster?
1,445,607,289,000
How to use wget to download files from Onedrive? (and batch files and entire folders, if possible)
Using Chrome (but Firefox will probably also work). Open DevTools Click the Download button. Download but cancel immediately Open the 'Network' tab in DevTools. Search for 'Zip?authKey=' in DevTools and open it (click). This is a POST request. Click 'View source' to the right of 'Form data' at the bottom. Construct ...
How to download files and folders from Onedrive using wget?
1,445,607,289,000
When I run several jobs on a head node, I like to monitor the progress using the command top. However, when I'm using PBS to run several jobs on a cluster, top will of course not show these jobs, and I have resorted to using 'qstat'. However the qstat command needs to be run repeatedly in order to continue monitoring ...
If you want to be a super-boss, you can always use 'pbstop' It's basically a PBS cluster version of what 'htop' is for local processes. (Note that your cluster may not have this installed. Ask the admins for it!) (Also, supports interactive filtering by user, queue, etc) EG:
PBS equivalent of 'top' command: avoid running 'qstat' repeatedly
1,445,607,289,000
After importing several 1000 Files from a camera onto a hard drive I realized, that the counter, used in the process of renaming the file - does not start from 0. This leads to file structure like this: My vacation 2018-05-03 2345.jpg My vacation 2018-05-03 2346.jpg My vacation 2018-05-04 2347.jpg I would like to bat...
In the file names, we need to substitute a sequence of digits followed by dot — \d+. — by a 4-zero padded counter followed by dot — sprintf("%04d.", ++$c). rename -n -- 'our $c; s/\d+\./sprintf("%04d.", ++$c)/e' *.jpg For no zero padding, we don't need sprintf, but only to concatenate the counter and the dot. Since t...
Replacing counter in a filename for all files in a directory
1,445,607,289,000
I'm used to IBM i (AS/400) batch processing with flexible queueing configuration possibilities. I'm searching a similar facility for Linux Batch processing. Most important is that one job at a time being taken from the queue and executed. After that, the queue is scanned for more entries. If there are any, the next ta...
ts - task spooler. A simple unix batch system should be up for the task. It runs a task spooler/queue server and you can add a new task with a simple command like: tsp yourcommand You can specifify the number of slots - aka how many jobs should be executed at a time. By default this is set to one, AFAIK. It also has...
Batch Processing with one task at a time
1,445,607,289,000
I am launching non interactive jobs using batch, and I would like to increase the load limiting factor in order to use all 8 of my cores. I am on Ubuntu 16.04 LTS. From what I understand, batch uses atd to do the jobs. Jobs start when the load factor goes under a threshold, called the load limiting factor. It is said ...
Found a solution: Create a file: /etc/init/atd.override Add a line exec atd -l 7.2 Then sudo service atd restart It has to do with how the 'Upstart init daemon' works. Explanations there: http://linux.die.net/man/5/init If the file /etc/init/atd.override already exists with an line starting with exec, edit this line...
atd, batch // Setting the load limiting factor
1,445,607,289,000
I have a surveillance camera and a program records videos when motion is detected. Basically, this program saves the video in a very heavy format. My solution was to call a script that converts the video using ffmpeg. The script is called each time a video is made. The conversion takes a relatively short time, but a l...
You can use batch program that is part of at package (tools for job queuing). It is installed by default on many systems.
How can I queue processes?
1,445,607,289,000
It seems that I cannot use ./ in qsub as in qsub -q hpc-pool ./myScript.sh where myScript.sh contains several ./. After checking, ./ somewhat is translated to ~/. Why is this the case?
Batch jobs submitted by qsub are executed in your home directory by default. Some versions of qsub support the -d option to specify a different directory. To execute the script in the same directory where you ran qsub, use qsub -d "$PWD" -q hpc-pool ./myScript.sh If the -d option is not available, you can access the ...
Current directory ./ in qsub?
1,445,607,289,000
I've got an old Mac with 24 cores, and I'd like to run several hundred/thousands one-core jobs automatically. I've made a bash script that runs the processes in the background, but if I set too many going at once the computer freezes (apparently 300 is okay, 400 too much...). Ideally, what I'd like to do is run 24...
I encountered a similar problem recently. As far as I know you have two options: xargs -0 -P 24 -L 1 and Gnu Parallel For example, to convert every flac file found by the find command to ogg I tried running: find -name "*.flac" -print0 | xargs -0 -P 24 -L 1 oggenc This runs up to -P 24 processes at a time using -L ...
queue-like behaviour for multiple one-core jobs on single machine? [duplicate]
1,445,607,289,000
I need to get a clean txt document and my first approach is to use aspell. The issue is I need it on batch, no interactive mode. Every txt file is piped to aspell and must be returned a new document with the non-dictionnary words deleted. I've found just the inverse behaviour: list the non-dictionary words using cat ...
sed -E -e "s/$(aspell list <file | sort -u | paste -s -d'|' | sed -e 's/^/\\b(/; s/$/)\\b/' )//g" \ file > newfile This uses command substitution $(...) to insert the output of aspell list <$file into a sed search and replace operation. aspell's output is also unique sorted and paste is used to joi...
filter document via aspell
1,445,607,289,000
Consider a simple processing queue like: cat list.txt | xargs -n1 -P20 process.sh (-P or --max-procs) How to have something like that in AIX ?
You could emulate the same thing by replacing your xargs by a ksh script. Eg: #!/bin/ksh nproc=0 max=20 trap 'let nproc--' sigchld while read file do while [ $nproc -ge $max ] do sleep 1 done process.sh "$file" & let nproc++ done wait The shell variable nproc counts the number of processes ...
How to have a process queue in AIX like xargs with "--max-procs"?
1,445,607,289,000
I am still pretty new to linux and have been trying very hard at getting this right. Please help me to get this right. I am trying to merge 2 videos (1 from each folder) multiple times in like a batch process, automatically 1 set after the next. I am trying to do it with ffmpeg and for loop in order to take one file ...
In your first example, ${filename%} doesn't change $filename at all, and as you told ffmpeg to open the .mp4 file with the concat demuxer -f concat, the error message should have been <actual name of $filename>: Invalid data found when processing input, but you recieved No such file or directory, so I suspect the glob...
ffmpeg merge multiple sets of 2 videos in for loop
1,445,607,289,000
How can I count the unique log lines in a text file only until the first "-" and print the line with the count org.springframework. - initialization started org.springframework. - initialization started pushAttemptLogger - initialization started pushAttemptLogger - initialization started example result org.springfram...
cut -f1 -d'-' inputfile | sort | uniq -c cut -f1 -d'-' will treat the file as dash-delimited and return only the first column in each line. sort is necessary for uniq to work properly. uniq -c shows only unique lines from the sorted input, including a count.
Count unique lines only to a set pattern
1,445,607,289,000
I would like write a batch script that checks used or available memory allow me to run commands if available memory less than X mb. I googled but page they refer didn't work for me I am using centos 7 basically I would like to do if availablememory < 26000m do command=forever stopall do command=pkill -f checkurl.php ...
if [ $(awk '/^MemAvailable:/ { print $2; }' /proc/meminfo) -lt 123456 ]; then : do someting done
batch script run command if available memory less than X mb
1,445,607,289,000
I have a bunch of images that I'd like to rename as follows: *.png.png --> *.png *.jpeg.jpg --> *.jpg *.JPEG --> *.jpg The only thing I've tried thus far is mv *.png.png *.png, but I knew that wouldn't work, but took a chance nevertheless. Is there a simple (or maybe not) way to batch rename files with this pattern?...
Here is something using find to rename *.png.png -> *.png: find ./ -name '*.png.png' -type f \ -exec sh -c 'mv {} ./$(basename -s .png.png {}).png' \; It isn't really gerenic, so you have to customize it for the other file extensions.
Mac Terminal - rename *.png.png to *.png
1,445,607,289,000
In batch: @echo off :step1 if exist "file1.txt" (GOTO step2) ELSE (GOTO X) :step2 if exist "file2.txt" (GOTO Z) ELSE (GOTO Y) :X run the script from the beginning and file1.txt and file2.txt are created and the rest of the script is executed :Y run the commands to file1.txt and run the rest of the script :Z run the c...
After knowing exactly what your batch script should do, I would start with simplifying it a bit: @echo off if exist "file1.txt" goto skip_part1 run the script from the beginning and file1.txt and file2.txt are created and the rest of the script is executed :skip_part1 if exist "file2.txt" goto skip_part2 run the comma...
how to create a bash script, with alternative of "goto" and "labels"
1,445,607,289,000
I'm on OpenSUSE 12.1, so no tmux, and we're not allowed to install anything - wget is too old to download a binary as well. Often I and other users have to run long scripts that take several hours, and our SSH client will crash in the middle. I'm aware that this is a bad practice but my opinion isn't valued. What's a...
One option would be screen, if it is available. (You mentioned tmux, but not screen) Another option would be to run the script with "nohup" which will disassociate it from your shell. You would then need to use its pid to monitor it. Redirecting the output to files would also be recommended.
What's the best way to run a long script without the SSH client crashing?
1,445,607,289,000
I've been reading the recent blogpost "Winding down my Debian involvement" by Michael Stapelberg. Sad details aside, it's been mentioned that within Debian infrastructure batch jobs run four times a day at XX:52 UTC: When you want to make a package available in Debian, you upload GPG-signed files via anonymous FTP. T...
It is not random, and it is something that a system administrator should think about. Notice that your cron.hourly, your cron.daily, your cron.weekly, and your cron.monthly are all run at different times. These times have varied over the years, and have been moved back and forth, because these jobs interact with one ...
Starting batch jobs at exact time slightly before the new hour starts
1,445,607,289,000
I have a submit script looks like below, it tries to run a large number of instances of csce.py in backgrounds with 3 nodes.... in a laptop, this usually could successfully automatically distribute all the background tasks into 16 cores.... However, I am not sure if in a cluster, it would also automatically distribute...
No, if you would have multiple nodes (machines) there is nothing in there that takes advantages of that, everything will run on the machine you run this script. The & at the end of the csce.py line just makes the operation run in the background on the current machine. So wit this setup you will get 4x12x9 tasks runnin...
submitting jobs to get 3 nodes running parallel executions
1,445,607,289,000
I have multiple text files, and I wish to extract specific columns from these files and save them to *_2.txt files. awk '{print $(NF-3), $5}' *.txt > *_2.txt But this command is not working. How can I achieve this batch column extraction using awk? Input: a.txt aaa bbb ccc 109.6136 93.1900 1.0000 ...
You have to do this within AWK script like that: awk 'FNR == 1 { sub(/\.txt$/, "_2.txt", FILENAME) } { print $(NF-3), $5 > FILENAME }' *.txt
batch awk print from multiple input file to multiple output file
1,445,607,289,000
I'm trying to rename multiple numbered files according to a list of names. Example: 1.pdf, 2.pdf, …, n.pdf And a file called names.txt, with a value per line: Fabio Joao n-name So we will have 1.pdf → Fabio.pdf 2.pdf → Joao.pdf n.pdf → n-name.pdf Any ideas on how to accomplish this?
If the files are really just "lineNumber.pdf", then this is very easy to do. In the shell: c=0 while IFS= read -r name; do ((c++)) echo mv -- $c.pdf "$name.pdf" done < names.txt Once you're sure that works as you want it, remove the echo from the mv command. If you have very many files, you might want to cons...
Rename multiple files according using a names-list
1,445,607,289,000
I have submitted a job on a PBS managed cluster using qsub -l nodes=5:ppn=16. My job is queued and is waiting for other jobs to be completed. Is there a command that allows me change the number of allocated nodes for queued jobs? I can simply delete the job using qdel and submit it again with more number of nodes. Ho...
You could try qalter, but it might be that there are restrictions on what you can change. qalter -f <jobID> shows a list of resources available. qalter -l nodes=5:ppn=16 will be used to alter the nodes.
Increase allocated nodes for queued jobs on a PBS cluster
1,445,607,289,000
I have a bunch of files in a single directory that I would like to rename as follows, example existing names: 1937 - Snow White and the Seven Dwarves.avi 1940 - Pinocchio.avi Target names: Snow White and the Seven Dwarves (1937).avi Pinocchio (1940).avi Cheers
If you have the Perl based rename (sometimes known as prename) this is indeed possible. If you understand Regular Expresssions it's even straightforward. rename -n 's!^(\d+) - (.*)\.(...)$!$2 ($1).$3!' *.avi What this does is split the source filename into three components. Using your first example these would be 19...
Batch rename long filenames of variable length with years
1,445,607,289,000
I have following image files in some directory which I want to be renamed: 8 -rw-rw-r-- 1 6661 sep 24 10:28 dbConnectionOkBostjan.png 8 -rw-rw-r-- 1 6548 sep 24 10:29 dbConnectionErrorBostjan.png 8 -rw-rw-r-- 1 5708 sep 24 10:29 btConnectionErrorBostjan.png 8 -rw-rw-r-- 1 5911 sep 24 10:30 btConnectionOkBostjan.png 8...
That can be done in one line, though for legibility I'll split. I echo the filename and modify it using sed in the target argument of mv: for i in *Bostjan*; do mv $i $(echo $i | sed s@Bostjan@@) done
multiple files rename - filenames patterns [duplicate]
1,445,607,289,000
I want to share my script to do this with Media Info CLI and python. At first I tried with pure bash but should have just gone python at first, much quicker and adaptable (for me). My task was to recursively go through all files in a specified folder (in this case on a NAS), and print as well as store in a txt file al...
usage: ./your_script_name.py ./your_path | tee output.txt if you want different/additional details from media info check those available with "mediainfo --Info-Parameters" #! /usr/bin/env python3 from glob import glob import os import sys import subprocess codecSummary = set() #dictionary path = sys.argv[1] prin...
Recursive (batch) video codec details with MediaInfo CLI
1,445,607,289,000
This is a bit of a crazy one, but I am wondering if it is even possible. I have maybe 300 folders in my /var/www folder that were all renamed to the same name [Name](Num) so kindred (19) for example. Almost every single one of these folders has a file called package.json which all have a name key value pair which then...
One of the better tools to use when you need to parse json files is jq. That makes it easy to extract the name field from the package.json file in a directory. Performing the rename is a simple bit of shell scripting: $ cd /var/www $ for d in */; do # *1 > if [ -f "${d}package.json" ]; then # *2 > new_name...
batch rename folders with value from json value in package.json
1,445,607,289,000
I am trying to batch rename the following files: art-faculty-3_29060055362_o.jpeg fine-arts-division-faculty-2016-2017-5_29165851925_o.jpeg theatre-faculty-2016-2017-1_29132529356_o.jpeg art-history-faculty-2016-2017-1_29060057642_o.jpeg music-faculty-2016-2017-1_29132523816_o.jpeg I would like to rename...
for i in *.jpeg; do echo mv "$i" "${i%faculty*}faculty.jpeg" ; done if okay as per requirements, remove echo to change the file names The perl rename command on my system has only the options -v -f -n $ rename -n 's/faculty\K.*(?=\.jpeg)//' *.jpeg art-faculty-3_29060055362_o.jpeg renamed as art-faculty.jpeg art-hist...
Rename command to delete substring
1,445,607,289,000
Hi there I'm trying to download a large number of files at once; 279 to be precise. These are large BAM (~90GB) each. The cluster where I'm working has several nodes and fortunately I can allocate multiple instances at once. Given this situation, I would like to know whether I can use wget from a batch file (see examp...
Expand the command into multiple wget commands so you can send them to SLURM as a list: while IFS= read -r url; do printf 'wget "%s"\n' "$url" done < sgdp-download-list.txt > wget.sh Or, if your sgdp-download-list.txt is just a list of wget command missing the wget at the beginning (which is what your example sugg...
wget — download multiple files over multiple nodes on a cluster
1,445,607,289,000
I need to convert a lot of *.wav in different folder, i try to use find and flac to convert all this without missing name of the track in the folder. This is the line I try to use : find ./ -type f -iname "*.wav" -exec sh -c flac -8 *.wav \; I don't know what missing but flac show me the man. I think I need some help...
There is no need to call a subshell for the find arguments here, you can call directly flac. Also the command you execute accepts multiple arguments, so you can call one flac process to convert all your files, like this: find . -type f -iname "*.wav" -exec flac -8 {} +
Need to convert a batch of wav in flac in different folder
1,445,607,289,000
For one file I know I can (being my video and sub files in the same directory): mkvmerge -o output-file.mkv --default-track 0 --language 0:es subtitle-file.ass video-file.mkv But how can I do the same for 50 files. My video and subtitle files name are the same: video-1.mkv video-2.mkv video-3.mkv video-1.ass video-2....
If each XYZ.mkv has a corresponding XYZ.ass, it's possible to use a for loop: for i in *.mkv; do if [ -f "${i%.*}".ass ] && [ ! -e "${i%.*}"-sub.mkv ]; then mkvmerge -o "${i%.*}"-sub.mkv "$i" --default-track 0 --language 0:es "${i%.*}".ass fi done Note: I did rearrange the order of your input files, ...
Batch mergin mkv video with subtitles using MKVToolNix
1,524,491,145,000
The Linux kernel minimal building requirements specifies that the calculator bc is required to build kernel v4.10, the minimal version of the tool being 1.06.95. What use is made of bc in this context, and why isn't the C language directly used instead of bc for these operations?
bc is used during the kernel build to generate time constants in header files. You can see it invoked in Kbuild, where it processes kernel/time/timeconst.bc to generate timeconst.h. This could be implemented as a C program which is built and run during the build, but it’s easier to use bc (which is small and common; i...
Why is 'bc' required to build the Linux kernel?
1,524,491,145,000
It looks like bc doesn't support float operations. When I do echo 1/8 | bc it gets me a zero. I checked the manual page bc (1), but it doesn't even mention float, so I wonder if it's supported?
bc doesn't do floating point but it does do fixed precision decimal numbers. The -l flag Hauke mentions loads a math library for eg. trig functions but it also means [...] the default scale is 20 scale is one of a number of "special variables" mentioned in the man page. You can set it: scale=4 Anytime you want (w...
Are operations on floats supported with bc?
1,524,491,145,000
What are the differences between dc and bc calculators? When should I use dc and when bc?
dc is a very archaic tool and somewhat older than bc. To quote the Wikipedia page: It is one of the oldest Unix utilities, predating even the invention of the C programming language; like other utilities of that vintage, it has a powerful set of features but an extremely terse syntax. The syntax is a reverse polish ...
How is bc different from dc?
1,524,491,145,000
I have a simple bash function dividing two numbers: echo "750/12.5" | bc I'd like to take the output from bc and append /24 and pipe said result to another instance of bc. Something like: echo "750/12.5" | bc | echo $1 + "/24" | bc Where $1 is the piped result. P.S. I realize I could just do echo "750/12.5/24" | bc ...
In the simplest of the options, this does append to the pipe stream: $ echo "750/12.5" | { bc; echo "/24"; } 60 /24 However that has an unexpected newline, to avoid that you need to either use tr: $ echo "750/12.5" | { bc | tr -d '\n' ; echo "/24"; } 60/24 Or, given the fact that a command expansion removes trailing...
Append to a pipe and pass on?
1,524,491,145,000
I often use bc utility for converting hex to decimal and vice versa. However, it is always bit trial and error how ibase and obase should be configured. For example here I want to convert hex value C0 to decimal: $ echo "ibase=F;obase=A;C0" | bc 180 $ echo "ibase=F;obase=10;C0" | bc C0 $ echo "ibase=16;obase=A;C0" | b...
What you actually want to say is: $ echo "ibase=16; C0" | bc 192 for hex-to-decimal, and: $ echo "obase=16; 192" | bc C0 for decimal-to-hex. You don't need to give both ibase and obase for any conversion involving decimal numbers, since these settings default to 10. You do need to give both for conversions such as b...
Understand "ibase" and "obase" in case of conversions with bc?
1,524,491,145,000
Sometimes I need to divide one number by another. It would be great if I could just define a bash function for this. So far, I am forced to use expressions like echo 'scale=25;65320/670' | bc but it would be great if I could define a .bashrc function that looked like divide () { bc -d $1 / $2 }
I have a handy bash function called calc: calc () { bc -l <<< "$@" } Example usage: $ calc 65320/670 97.49253731343283582089 $ calc 65320*670 43764400 You can change this to suit yourself. For example: divide() { bc -l <<< "$1/$2" } Note: <<< is a here string which is fed into the stdin of bc. You don't ne...
Doing simple math on the command line using bash functions: $1 divided by $2 (using bc perhaps)
1,524,491,145,000
I am evaluating the expression 6^6^6 using python and bc separately. The content of the python file is print 6**6**6. When I execute time python test.py, I get the output as real 0m0.067s user 0m0.050s sys 0m0.011s And then, I ran the command time echo 6^6^6 | bc which gave me the following o...
Python imports a large number of files at startup: % python -c 'import sys; print len(sys.modules)' 39 Each of these requires an even greater number of attempts at opening a Python file, because there are many ways to define a module: % python -vv -c 'pass' # installing zipimport hook import zipimport # builtin # in...
python vs bc in evaluating 6^6^6
1,524,491,145,000
I'm trying to do a hex calculation directly with bc, I already specified the scale. echo 'scale=16;c06b1000-c06a5e78' | bc But I still get a zero. What could be wrong?
echo 'ibase=16;C06D1000-C06A5E78' | bc 176520 Note that only UPPER CASE hex digits are supported as lower case ones would conflict with function and variable names, which is why you got 0 in your example (var1 - var2) If you need the answer in hex too, just set the obase variable: echo 'obase=16;ibase=16;C06D1000-C06...
Does bc support hex calculations?
1,524,491,145,000
I've been using bc to convert numbers between binary to hex, octal to decimal and others. In the following example, I was trying to convert base 16 (hex) number to binary, octal and decimal. I don't have any problem with the first 2 attempts. $ echo 'ibase=16; obase=2; FF' | bc 11111111 $ echo 'ibase=16; obase=8; F...
Once ibase=16 is done, further input numbers are in hexadecimal, including 10 in obase=10 which represents the decimal value 16. So either set obase before, or set it after, using the new input base (now hexadecimal): $ echo 'obase=10; ibase=16; FF' | bc 255 $ echo 'ibase=16; obase=A; FF' | bc 255
bc: Why does `ibase=16; obase=10; FF` returns FF and not 255? [duplicate]
1,524,491,145,000
echo "scale=3;1/8" | bc shows .125 on the screen. How to show 0.125 if the output result is less than one?
bc can not output zero before decimal point, you can use printf: $ printf '%.3f\n' "$(echo "scale=3;1/8" | bc)" 0.125
How to show zero before decimal point in bc?
1,524,491,145,000
The only calculator I know is bc. I want to add 1 to a variable, and output to another variable. I got the nextnum variable from counting string in a file: nextnum=`grep -o stringtocount file.tpl.php | wc -w` Lets say the nextnum value is 1. When added with 1, it will become 2. To calculate, I run: rownum=`$nextnum+1...
The substring inside the ` ` must be a valid command itself: rownum=`echo $nextnum+1 | bc` But is preferable to use $( ) instead of ` `: rownum=$(echo $nextnum+1 | bc) But there is no need for bc, the shell is able to do integer arithmetic: rownum=$((nextnum+1)) Or even simpler in bash and ksh: ((rownum=nextnum+1))...
Calculate variable, and output it to another variable
1,524,491,145,000
#!/bin/bash q=$(bc <<< "scale=2;$p*100") head -n$q numbers.txt > secondcoordinate.txt That's just part of the script, but I think it's enough to clarify my intentions. p is a variable with just two decimals, so q should be an integer... Nevertheless, bc shows, for example, 10.00 instead of 10. How can I solve this?...
You can't do this with the obvious scale=0 because of the way that the scale is determined. The documentation indirectly explains that dividing by one is sufficient to reset the output to match the value of scale, which defaults to zero: expr1 / expr2 The result of the expression is the quotient of the two expression...
how to make bc to show me 10 and not 10.00
1,524,491,145,000
bash has a handy file .bash_history in which it saves the history of commands and on the next execution of bash the history is populated with saved commands. Is it possible to save bc command history to a file in the same way and then load it on startup so that bc history is preserved? I tried reading GNU bc manual an...
If you aren't happy with the command line editing features that are built into a program, you can run it through rlwrap. This is a wrapper around a command line processor (a REPL) that lets you edit each line before it's sent. Rlwrap uses the readline library and saves history separately for each command. Running rlwr...
Is it possible to save `bc` command line history?
1,524,491,145,000
High, I need to test my arbitrary precision calculator, and bc seems like a nice yardstick to compare to, however, bc does truncate the result of each multiplication to what seems to be the maximum scale of the involved operands each. Is there a quick way to turn this off or to automatically set the scale of each mul...
You can control the scale that bc outputs with the scale=<#> argument. $ echo "scale=10; 5.1234 * 5.5678" | bc 28.52606652 $ echo "scale=5; 5.1234 * 5.5678" | bc 28.52606 Using your example: $ bc <<< 'scale=2; 1.5 * 1.5' 2.25 You can also use the -l switch (thanks to @manatwork) which will initialize the scale to 2...
BC—automatic full precision multiplication [duplicate]
1,524,491,145,000
I've always found bc kind of mysterious and intriguing. It was one of the original Unix programs. And it's a programming language unto itself. So I gladly take any chance I can find to use it. Since bc doesn't seem to include a factorial function, I want to define one like so: define fact(x) { if (x>1) { return ...
Save your function definitions in a file like factorial.bc, and then run bc factorial.bc <<< '1/fact(937)' If you want the factorial function to always load when you run bc, I'd suggest wrapping the bc binary with a shell script or function (whether a script or function is best depends on how you want to use it). Scr...
How to define a `bc` function for later use?
1,524,491,145,000
In Ubuntu 14.04.1 LTS 64-bit bash I am declearing floating point variables by multiplying floating point bash variables in bc with scale set to 3; however, I cannot get the number of digits after the decimal point to be zero and get rid of the zero to the left of the decimal point. How can I transform, say 0.005000000...
A simple way is to use printf: $ printf "%.3f\n" 0.005000000000 0.005 To remove the leading 0, just parse it out with sed: $ printf "%.3f\n" 0.005000000000 | sed 's/^0//' .005
Bash limiting precision of floating point variables
1,524,491,145,000
I'm trying to calculate the average entropy of files contained in a folder using: { echo '('; find . -type f -exec entropy {} \; | \ grep -Eo '[0-9.]+$' | \ sed -r 's/$/+/g'; echo '0)/'; find . -type f | wc -l; } | \ tr -d '\n' | bc -l entropy being an executable which calculates the Shannon entropy of a file...
And this works too: echo '(2.1+2.1)/2' | bc -l Ah, but did you try: echo '(2.1+2.1)/2' | tr -d '\n' | bc -l (standard_in) 1: syntax error Using echo -n will accomplish the same thing -- there's no terminating newline, and that's your problem.
Cannot sum numbers received from stdin using bc
1,524,491,145,000
I have a file with the following: 37 * 60 + 55.52 34 * 60 + 51.75 36 * 60 + 2.88 36 * 60 + 14.94 36 * 60 + 18.82 36 * 60 + 8.37 37 * 60 + 48.71 36 * 60 + 34.17 37 * 60 + 42.52 37 * 60 + 51.55 35 * 60 + 34.76 34 * 60 + 18.90 33 * 60 + 49.63 34 * 60 + 37.73 36 * 60 + 4.49 I need to write a shell command or Bash script ...
This awk seems to do the trick: while IFS= read i; do awk "BEGIN { print ($i) }" done < math.txt From here Note that we're using ($i) instead of $i to avoid problems with arithmetic expressions like 1 > 2 (print 1 > 2 would print 1 into a file called 2, while print (1 > 2) prints 0, the result of that arithmetic e...
How can I evaluate a math equation, one per line in a file?
1,524,491,145,000
If you load the bc math library you get the trig functions s() and c() and a() which are sine, cosine, and arctangent respectively. Why these three functions? I know why it's those three from the mathematical perspective: it's because those are the three you need to translate directly between Cartesian and polar coord...
Not a full answer, but perhaps somewhat useful. More of a list of examples of use of trig functions in early adaptions. Also a look into the UNIX world. ALGOL Interesting paper concerning the history: The History of the ALGOL Effort, by HT de Beer ALGOL was developed back in 1950's. In a joint meeting between Europ...
Who decided the bc math library will define sine cosine and arctangent?
1,524,491,145,000
I want to compare two numbers with bc. Per this highly rated answer on StackOverflow, I can do it in a manner as such: printf '%s\n' '1.2 > 0.4' | bc bc sends 1 to STDOUT, indicating that the statement is true (it would have returned 0 if the statement was false). Per the POSIX page for bc: Unlike all other operator...
Perhaps I am misinterpreting, but this language seems to disallow the syntax used in the above example. That example assumes GNU bc, which adds its own extensions to the bc language. As documented in its manual, you should use the -s switch to make it process the exact POSIX bc language, or the -w switch if you want...
bc: does POSIX prohibit standalone use of relational operators?
1,524,491,145,000
I want to store the value of 2^500 in the variable DELTA. I'm doing export DELTA=$(echo "scale=2; 2^500" | bc) but this does not set DELTA to 3273390607896141870013189696827599152216642046043064789483291368096133796404674554883270092325904157150886684127560071009217256545885393053328527589376. Instead, it sets it to...
echo "scale=2; 2^500" | bc | tr -d '\n\\' Output: 3273390607896141870013189696827599152216642046043064789483291368096133796404674554883270092325904157150886684127560071009217256545885393053328527589376
Store 2^500 in a variable in bash
1,524,491,145,000
I defined the cbrt function to return a cube root. I need to get an integer back (even if it is close to the cube root, it will be acceptable in my case). However, when I put the scale as 0 to get an integer, I get numbers which are grossly incorrect. What is going on and how do I get an integer cube root out? bc ...
Setting scale before calling cbrt() has the effect of setting the scale whilst cbrt() is evaluated. The way around it is to stash the scale as part of the function: define cbrt(x) { auto z, var; z=scale; scale=5; var = e(l(x)/3); scale=z; return (var); } which when called gives: scale=0; cbrt(1000000) 99.99998 Which...
BC not handling scale = 0 correctly
1,524,491,145,000
Is there a simple way to separate a very large number per thousands with printf, awk, sed ? So 10000000000000 become 10 000 000 000 000 Thanks
A simple combination of sed and rev could be employed - echo "I have 10000013984 oranges" | rev | sed "s/[0-9][0-9][0-9]/& /g" | rev first rev is required to replace number from right to left , and the second one for bringing back the original string.
printf, awk ... How to format a number with space to the thousands
1,524,491,145,000
I am using shell scripting and I am using the following expression: A=`echo "(( (($a / $b) ^ 0.3) -1 ))" |bc -l` I want to have a real number as an exponent. I noticed that If I place 0.3, it rounds off to an integer and takes the power of zero. Similarly if I use 5.5 or 5.9 in place of 0.3 in the above expression, I...
Why can't you use awk or perl one-liner to handle it? echo "$a $b" | awk '{ print ((($1/$2)^0.3) -1); }'
Shell Scripting: calculate power of a number with a real number as an exponent
1,524,491,145,000
I need to pass certain variable to bc to get the output in floating point, var1=$((<some operation>)) var2=$((<some operation>)) #Needs var1 var3=$((<some operation>)) #Needs var2 bc -l <<< $var3 #Need output in Floating points Output: (standard_in) 1: illegal character: $ Anyway to overcom...
Simple quotes don't expand $ variable. You have to use double quotes: var3=`bc <<< "scale=2; $var2"` On the other hand, $var1 and $var2 won't store float (bash doesn't manage them), so you bc instead. diff=$(($epoc2-$epoc1)) var1=$(bc <<< "scale=3 ; $diff / 60") var2=$(bc <<< "scale=3 ; $var1 / 57") var3=$(bc <<< "sc...
Anyway to pass a variable to bc, having a command to be executed?
1,524,491,145,000
How do I get bc to start decimal fractions with a leading zero? $ bc <<< 'scale=4; 1/3' .3333 I want 0.3333.
bc natively does not support adding zero. Workaround is: echo 'scale=4; 1/3' | bc -l | awk '{printf "%.4f\n", $0}' 0.3333 \n  – terminate the output with a newline. %f  – floating point %.4f – the number of digits to show.  This specifies 4 digits after the decimal point.
How do I get bc to start decimal fractions with a leading zero
1,524,491,145,000
How can I add a command line calculator to my bash? I have found some, but all of them use the full stop as decimal mark, but I want to have it to use the comma as decimal mark as most of the world does, see picture: (source wikipedia) blue: Full stop/Period (.) green: Comma (,) red: Momayyez (٫) gray: Data unavaila...
I have found a solution. calc () { awk ' function asin(x) { return atan2(x, sqrt(1-x*x)) } function acos(x) { return atan2(sqrt(1-x*x), x) } function atan(x) { return atan2(x,1) } function tan(x) { return sin(x)/cos(x) } BEGIN { pi=atan(1)*4; print '"$(echo "$@" | tr , .)}" | tr . , } This one ...
how to add command line calculator to bash that uses comma as decimal mark?
1,524,491,145,000
I understand bash and some other interpreters only perform arithmetic for integers. In the following for loop, how can I accomplish this? I've read that bc can be used but am not sure how to use bc in this situation. total=0 for number in `cat /path/to/file`; do total=$(($total+$number)) done average=$(($to...
You may not want to use bc for this. Perhaps awk would work better: awk '{sum+=$1};END{print sum/NR}' /path/to/file
Perform floating point arithmetic in shell script variable definitions [duplicate]
1,524,491,145,000
I read topics about how to get bc to print the first zero, but that is not exactly what I want. I want more... I want a function that returns floating point numbers with eight decimal digits. I am open to any solutions, using awk or whatever to be fair. An example will illustrate what I mean: hypothenuse () { ...
You can externalize formatting this way, using printf: printf "%0.8f" ${x} Example: x=3 printf "%0.8f\n" ${x} 3.00000000 Note: printf output depends on your locale settings.
How to get bc to print trailing zeros?
1,524,491,145,000
This came out of one of my comments to this question regarding the use of bc in shell scripting. bc puts line breaks in large numbers, e.g.: > num=$(echo 6^6^3 | bc) > echo $num 12041208676482351082020900568572834033367326934574532243581212211450\ 20555710636789704085475234591191603986789604949502079328192358826561\ ...
echo puts a space between each two arguments. The shell considers the newline in $num just a word separator (just like space). lines="a b c" set -x echo $lines # several arguments to echo echo "$lines" # one argument to echo See this answer (by the OP himself) for a more detailed explanation.
Automatic transformation of newlines in shell variable assignment
1,524,491,145,000
I read how to calculate using the command line calculator and a HERE-document, but nevertheless I do not get what I expected and can not find my error, what I did in the shell was: bc << HERE >ibase=2 >obase=16 >1001 >HERE 100 I expected to get 9 as result since binary 1001 is hexadecimal 9, but I got 100.
Because you set ibase=2 first, you need to use obase=10000: $ echo 'ibase=2; obase=10000; 1001' | bc 9
Difficulty converting from binary to hexadecimal using bc
1,524,491,145,000
When I'm performing float operations in shell using bc, the result is not the same if I use a regular calculator. Am I doing something wrong? For example, I need to find a volume of a sphere. User inputs the radius value. pi = 3.14 volume=$(echo "scale = 2; (4 / 3) * $pi * ($r ^ 3)" | bc) echo "Volume is $volume" If...
You need to understand the meaning of the scale of an expression in bc. bc can do arbitrary precision (which doesn't necessarily mean infinite precision) while your calculator will probably have the precision of the float or double data type of your processor. In bc. The scale is the number of decimal after the dot, s...
Float operations with bc not precise?
1,524,491,145,000
I was trying to think of a quick and illustrative way to generate a non-successful exit status and thought dividing by zero with the bc would be a good idea. I was suprised to discover that although it does generate a runtime error, the exit status is still 0: $ echo 41 + 1 | bc 42 $ echo $? 0 $ echo 42/0 | bc Runtime...
bc implementations differ a bit in their return status, but the general idea is that if you supply valid input then bc exits with the status 0. 42/0 is valid input: there's no read error, and it's even a syntactically valid expression, so bc returns 0. If you passed a second line with another operation, bc would perfo...
Why does bc exit 0 when dividing by 0?
1,524,491,145,000
I have an expression "5+50*3/20 + (19*2)/7" I need to round it up to 3 decimal places. The answer to this is 17.92857142857143. When I use the script below it is giving me 17.928. The answer should be 17.929. read exp echo "scale=3; $exp" |bc -l And one more question is how to use printf to do the same task
Python seems have your preferred behaviour: $ echo 'print(round(' "5+50*3/20 + (19*2)/7" ', 3))' | python3 17.929
Evaluation an expression and rounding up to three decimals
1,524,491,145,000
Following code calculates the Binomial Probability of a success event k out of n trials: n=144 prob=$(echo "0.0139" | bc) echo -e "Enter no.:" read passedno k=$passedno nCk2() { num=1 den=1 for((i = 1; i <= $2; ++i)); do ((num *= $1 + 1 - i)) && ((den *= i)) done echo $((num / den)) } b...
FWIW, prob=$(echo "0.0139" | bc) is unnecessary - you can just do prob=0.0139 Eg, $ prob=0.0139; echo "scale=5;1/$prob" | bc 71.94244 There's another problem with your code, apart from the underflow issue. Bash arithmetic may not be adequate to handle the large numbers in your nCk2 function. Eg, on a 32 bit syst...
bc scale: How to avoid rounding? (Calculate small binomial probability)
1,524,491,145,000
Since the following command using bc does not work for numbers in scientific notation, I was wondering about an alternative, e.g. using awk? sum=$( IFS="+"; bc <<< "${arrValues[*]}" )
sum=$( awk 'BEGIN {t=0; for (i in ARGV) t+=ARGV[i]; print t}' "${arrValues[@]}" ) With zsh (in case you don't have to use bash), since it supports floating point numbers internally: sum=$((${(j[+])arrValues})) With ksh93: If you need the kind of precision that bc provides, you could pre-process the numbers so that...
How to sum a bash array of numbers (some in scientific notation)?
1,524,491,145,000
I run this command in the terminal: grep "bla bla blah" blah* | echo "Blah: $(wc -l) / $(ls | wc -l) * 100" And I get this output: Blah: 44 / 89 * 100 What I expect to see: 49.4 Is there a way to obtain the desired output using just the bash commands? I don't prefer scripts I am planning to pipe the output.
Your code says to print a string. It doesn't say anywhere that this string is in fact an arithmetic expression that you want evaluated. So you can't reasonably expect your expression to be evaluated. Your code is suboptimal. $(wc -l) will count the number of matches returned by grep, but there's a simpler way: run gre...
How to calculate values in a shell script?
1,524,491,145,000
This is a bc output, e.g.: Input: echo "scale=10; BLA-BLA-HERE-NOT-IMPORTANT" | bc Output: .3708446283953709207058828124021300754352578903651372655882743141882\ 77124645102027246581819139527644919407424570060822470537797066353573\ 96635.8038454068 days Two Questions: can the output be rounded to something like "0....
You can try something like this code: echo "scale = 4; 3.5678/3" | bc | tr '\n' ' ' Setting scale for bc is supposed to do the rounding job. You can substitute the division part with your desired command. The output of bc is again piped to tr, which converts the newline (\n) to white space. For the above command I g...
BC - no "\\n" at the end + start with zeros?
1,524,491,145,000
I'm trying to do an interface to bc so it can be used intuitively and without the annoyance of getting "stuck" in it. I haven't got around to test it that much, because I got stuck on another detail, namely how to present the result (which is, I think, a string). Rounding or truncating does not matter, either one is f...
Using zsh's own arithmetic, you could do: calc() printf '%.6g\n' $(($*)) alias 'calc=noglob calc' But that would mean you'd need to enter numbers as 123. for them to be taken as floating point and trigger a floating point calculation. You could work around that by appending . to any sequence of decimal digits that is...
Round/truncate digit in string in zsh (or with external tool)
1,524,491,145,000
I'm debugging code which contains quite a few bit shift operations, and I'm using bc a lot to look at what's happening on the bit level. Here's what I use: $ echo 'obase=2;598980975283696640' | bc 100001010000000000100000011000000011000000000111010000000000 Is there a simple way to get the output as whitespace-sepa...
I would use this simple function: nibbles () { echo "obase=2; $1" | bc | rev | while read -n4 a; do echo -n "$a ";done | rev ; echo; } $ nibbles 598980975283696640 1000 0101 0000 0000 0010 0000 0110 0000 0011 0000 0000 0111 0100 0000 0000
bc output binary as nibbles separated by whitespace
1,524,491,145,000
System: Ubuntu 22.04.3 LTS GNU bash, version 5.1.16(1)-release (x86_64-pc-linux-gnu) bc 1.07.1 Observation: Both ibase and obase are unset. echo "A0" | bc 90 echo "B0" | bc 90 echo "X0" | bc 90 Question: Why does bc interpret alpha characters as 9s by default? Why wouldn't an error message be preferable here?
From man bc on a GNU system (with GNU bc 1.07 or newer): A simple expression is just a constant. bc converts constants into internal decimal numbers using the current input base, specified by the variable ibase. (There is an exception in functions.) The legal values of ibase are 2 through 36. (Bases greater tha...
By default, bc interprets any alpha character as a 9
1,524,491,145,000
I want to perform some mathematical operations in the shelll. For example: 5+50*3/20 + (19*2)/7 I tried: #!/bin/bash read equ echo "scale=3; $equ" | bc -l Expected output: 17.929 My output: 17.928
bc is truncating, try this instead: printf "%.3f\n" $(echo "$equ" | bc -l)
How can I do basic calculations in a shell script?
1,524,491,145,000
I want to calculate an expression in shell. I use the following code: pi=$(echo "scale=10; 4*a(1)" | bc -l) i=3 d=`expr (1+c($pi*($i/10)+$pi))/2 | bc -l` But it says bad pattern: (1+c(3.1415926532*(3/10)+3.1415926532))/2 Why?
Because you're using expr in your last command where you probably should be using echo. P.S. I advise you to use the $(…) form in both bc commands (rather than `…`).
A bc problem about long expression
1,524,491,145,000
I would like to create an alias for bc that runs bc -l and specifies that pi=4*a(1). This way, I can start each session with pi already defined. What alias will do this?
I will answer your Question, but you should consider following the link provided by Julie Pelletier assuming you are using bash: alias bc-l-with-pi='bc -l <(echo "pi=4*a(1)")' explanation: we (ab)use the bash redirection to give bc a temporary file with the content "pi=4*a(1)". after that bc goes into interactive mo...
Start bc with pi defined
1,416,436,772,000
I have a CSV file generated by a script of mine, It gets CPU time used per user, however it gets this in seconds, i need it in hours so i need to divide each line by 3600. example input file **USER,TOTAL_CPU,AVERAGE_CPU user1,1234552.0,1234.3 user2,9999999.0,82772.6 user3,7777776227.9,282882,0** I can easily get what...
Awk solution: awk 'BEGIN{ FS=OFS="," } NR > 1{ $2 = sprintf("%.3f", $2/3600); $3 = sprintf("%.3f", $3/3600) }1' file The output: USER,TOTAL_CPU,AVERAGE_CPU user1,342.931,0.343 user2,2777.778,22.992 user3,2160493.397,78.578,0
divide two columns, not with each other
1,416,436,772,000
I have a big number: 2923174917395723957 that would be: 2,923*10^18 are there any parameters in bc that will give this OUTPUT? e.g.: $ echo '2923174917395723956 + 1' | bc 2,923*10^18 $ Or something similar...the point is that it must have a short look Thank you!
Try the printf command: $ printf "%e\n" 2923174917395723957 2.923175e+18 In your locale, it should use , instead of ., of course. You can also control the format more precisely such as: $ printf "%.3e\n" 2923174917395723957 2.923e+18 Some shells like bash have a built-in called printf which may be different from an...
BC - output normal form?
1,416,436,772,000
I am trying to divide two values in a loop using bc, and I have set that value as a variable. My problem is that I want that value to have 2 decimal places, but I am having trouble getting scale=2 to work while defined inside a variable. Here is my test file: cat file.txt Sc0000000_hap1 0 1200 32939 Sc0000000_ha...
avg=`scale=2; expr $sum / $divisor | bc ` You are setting a shell variable scale to 2 calculating the integer division using expr and passing that value to bc (read man expr) bc does not perform any calculations, it just outputs the number that was fed into it. Let bc do the work: avg=$(echo "scale=2; $sum / ($s...
Set scale for bc inside a variable
1,416,436,772,000
I am trying to translate a simple program to the command line using unix utilities. For example, if I have a frequency list (after piping through uniq and sort) 5 x 4 y 1 z I want to print out, instead of the frequencies, the fraction of the times they occur: 0.5 x 0.4 y 0.1 z (I have a python program that does this...
awk '{ f[$2] = $1; SUM += $1} END { for (i in f) { print f[i]/SUM, i } }' </tmp/data
How to divide a list of values by a number in command line?
1,416,436,772,000
I have written an .awk which executes some operation on a .tr file and writes the output to a file. The END section of .awk file prints this: printf("%15.2f\n%15.5f\n%15.2f\n%15.2f\n%15.2f\n%10.2f\n%10.2f\n%10.5f\n", rThroughput, rAverageDelay, nSentPackets, nReceivedPackets, nDropPackets, rPacketDeliveryRatio, rPacke...
Your script doesn't appear to initialize the variable energy_efficiency, so the first time around the loop echo "scale=9; $energy_efficiency+$val/$iteration_float" produces scale=9; +197645.74/1.0 which is a syntax error (bc apparently allows unary -, but not unary +) $ echo "scale=9; +197645.74/1.0" | bc (standard_...
(standard_in) 1: syntax error when using bc
1,416,436,772,000
I cannot find a way to close while statement.The following is my bash script code. bc << EOF a=0; while(a<10) a++; print a; EOF The ouput is not as expected, it prints all the a values other than the last one. Please help me.
The result of an operation is always printed unless it's an assignment. So, let's turn a++ into the assignment a=a+1. bc <<END_BC a = 0 while (a < 10) a = a + 1 print a, "\n" END_BC Alternatively, but slightly more cryptic (using an empty while loop): bc <<END_BC a = 0 while (++a < 10) print a, "\n" END_BC
how to close a while statement in bc script
1,416,436,772,000
On Ubuntu 14.04.1 64-bit LTS I am writing a shell script and if I define the start of the sequence used in the for loop with a variable instead of a constant I get really weird behavior and there are lots of errors from the bc calculator. You can run the following code snippet to reproduce the errors: #!/bin/bash S=0....
The problem turned out to be that the decimal point separator in my Ubuntu installation was set to , (comma) instead of . (dot). I changed it with the following command: sudo update-locale LC_NUMERIC="en_GB.UTF-8" And the problem was resolved.
Problematic bc calculation in shell script
1,416,436,772,000
I have object of class class X { private DateTime dt; "constructor, set/get" } I have one instance of this object serialized in file.bin. I want to show content of `file.bin on the Linux console in human readable way.
You can display the contents of a file with cat, but with binary files that will often result in "garbage". For binary files you can use od -x (or xxd): od -x file.bin that makes everything byte readable as hex words for any file (understanding what that means is more difficult and dependent on the program that wrote...
Convert serialized Java object to human readable
1,416,436,772,000
I have 3 variables and values: totalLines=14 outsideLines=6 multiplied=600 totalLines represents the total number of lines (100%), while outsideLines represents number of lines with the timestamp values outside certain limit. My purpose is to calculate the percentage of those outside lines. If I do this: percentage=$...
You can do this: percentage=$(echo "scale=2; $multiplied / $totalLines" | bc)
How to properly use bc to convert the value of percentage to floating point format?
1,416,436,772,000
I've written this if, that is obviously not working, and I still can't manage to get over it: #LASTEFFECTIVEHASH if (( $(echo "$LASTEFFECTIVEHASHMINVAL < $LASTEFFECTIVEHASH < $LASTEFFECTIVEHASHMAXVAL" | $BC -l) )); then echo "$DATESTAMP - LASTEFFECTIVEHASH=$LASTEFFECTIVEHASH is between $LASTEFFECTIVEHA...
Unlike for example python, bc does not support chained comparisons: a < b < c To perform both comparisons and require both to be true, use logical-and (requires GNU bc): (a < b) && (b < c) For example: $ a=104.9; b=136; c=136.9; if echo "($a < $b) && ($b < $c)" | bc -l | grep -q 1; then echo True; else echo False; f...
Checking that a decimal number is in a range in bc
1,416,436,772,000
When you run 'bc' on a GNU system, it prints out the following text: ~$ bc bc 1.07.1 Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006, 2008, 2012-2017 Free Software Foundation, Inc. This is free software with ABSOLUTELY NO WARRANTY. In contrast to several other GNU utilities: ~$ gcc --version gcc (Debian 8.3.0-6) 8....
bc follows the recommended GNU practices for copyright notices, which involves listing every single publication year, although the copyright notice here lists more years than saw bc releases (even including dc releases). The other tools only list the year of last publication, using gnulib’s version_etc function which ...
Why does GNU 'bc' have such a long copyright string?
1,416,436,772,000
I can pipe echo into bc. But I cannot do the same with "printf": it gives syntax error. ❯ echo "100-5" | bc 95 ❯ printf "%s" "100-5" | bc (standard_in) 1: syntax error
Just need a newline: printf '%s\n' "100-5" | bc In your present situation
Why I can pipe echo into bc, but I can't do the same with printf?
1,416,436,772,000
for i in {0..9} do T=$(bc<<<"8+$i*0.5") echo $T done I get : syntax error near unexpected token `T=$(bc<<<"8+$i*0.5")' I believe the problem is the $i. What am I doing wrong?
The problem is not $i, the problem is in your for construct syntax. You need a newline or ; before do (if used right after the for declaration): for i in {0..9}; do T=$(bc <<<"8+$i*0.5") echo "$T" done Or for i in {0..9} do T=$(bc <<<"8+$i*0.5") echo "$T" done For clarity, it's better to use whites...
use loop variable for calculation bash
1,416,436,772,000
I've found that there is an upper-bound on your subscripts/indices in an array in GNU bc. Running interactively and asking to let arr[100000000]=42 returns an error: Runtime error (func=(main), adr=17): Array arr subscript out of bounds. This array size limit isn't listed among bc's limits, and it doesn't appear the...
You can see the bc limits: $ echo 'limits' | bc BC_BASE_MAX = 2147483647 BC_DIM_MAX = 16777215 BC_SCALE_MAX = 2147483647 BC_STRING_MAX = 2147483647 MAX Exponent = 9223372036854775807 Number of vars = 32767 And into man bc (1p) we see: Arrays are singly dimensioned and can contain up to {BC_DIM_M...
What's the upper-bound for an array index/subscript in GNU bc?
1,416,436,772,000
Is there a more elegant way than using xargs -Ix for the following? echo "283" | xargs -Ix bc -l -e "scale=2; l( x )/l(10)"
I don't really see a reason for xargs here: printf 'scale=2; l(%s)/l(10)\n' "283" | bc -l Alternatives for when the number is read from a file: awk '{ printf "l(%s)/l(10)\n", $1 }' file | bc -l -e 'scale=2' (that's assuming a bc that has -e), or without bc at all: awk '{ printf "%.2f\n", log($1)/log(10) }' file
How to pipe a number into bc elegantly?
1,416,436,772,000
I'm trying to compare two floats in bash and something is going wrong. Here is the code sample based on solution here num1=0.502E-01 num2=0.01 echo $num1'>'$num2 | bc -l echo $num2'>'$num1 | bc -l I expect the output of 1 for first echo and 0 for second echo, but instead I get 0 for the first and 1 for the second. Wh...
awk can certainly do float comparisons if called from your shell script. num1=0.502E-01 num2=0.01 awk -v a="$num1" -v b="$num2" 'BEGIN{print(a>b)}' 1 awk -v a="$num1" -v b="$num2" 'BEGIN{print(b>a)}' 0
Wrong output in comparing floats
1,416,436,772,000
I want to raise a fraction (fraction is calculated on first loop) to a decimal power (second loop), however, I always get 1 as a result. I want to store the output of the second loop in an array as well. Any ideas how to work around this? Thank you! # # vector of vertical pressure levels levs=($(seq 200.0 50.0 900.0))...
There are a couple of problems associated with your attempt. The immediate problem being using rho as a literal string when raising it as a power constant to bc bc <<<"$j ^ $rho" Even with that the code does not work, bc does not take fractional numbers for exponents. You get an error non-zero scale in exponent. You ...
Raise each element of an array to a power and store output to a new array in bash
1,416,436,772,000
I am trying to calculate what is the % of successful queries in apache log. I have two commands: cat access_log|cut -d' ' -f10|grep "2.."|wc -l and cat access_log|cut -d' ' -f10|wc -l They return me the number of successful queries and total queries number. I want to calculate what is the % of successful requests us...
Try this: echo $(( 100 * $( cut -d' ' -f10 access_log|grep "2.."|wc -l) / $(cut -d' ' -f10 access_log|wc -l) )) Bash can only handle integers.
How to calculate % of successful queries
1,416,436,772,000
I recently read about bc and found that it supports obase upto 999. Can anyone point me to the numeral set for bc for base greater than 16.
Yes, bc can process numbers with bases up to 999. As an example: $ echo "ibase=10;obase=40;3*40^2+7" | bc 03 00 07 Or, as it should be "307" = 3*40^2 + 0*40^1 + 7*40^0. Or 4807 in decimal. $ echo "ibase=10;obase=10;3*40^2+7" | bc 4807 So, the values are printed as a two digit (decimal) number with an space as sep...
What is the numeral for base greater than 16 in bc?
1,416,436,772,000
I am trying to multiply array values with values derived from the multiplication of a loop index using bc. #!/bin/bash n=10.0 bw=(1e-3 2.5e-4 1.11e-4 6.25e-5 4.0e-5 2.78e-5 2.04e-5 1.56e-5 1.29e-5 1.23e-5 1.0e-5) for k in {1..11};do a=$(echo "$n * $k" | bc) echo "A is $a" arn=${bw[k-1]} echo "Arn is ...
bc doesn't support the scientific format. Use something that does. For example, Perl: a=$(perl -e "print $n * $k" ) arn=${bw[k-1]} b=$(perl -e "printf '%.2E', $arn * $a") echo $a $b Output: 10 1.00E-02 20 5.00E-03 30 3.33E-03 40 2.50E-03 50 2.00E-03 60 1.67E-03 70 1.43E-03 80 1.25E-03 90 1.16E-03 100 ...
bash array multiplication using bc
1,416,436,772,000
I ran into an issue where bc does not have boolean expressions in the AIX system. Wondering if there is a replacement command so I don't have make my code any longer? This is in a bash script. Here is what I had: percent=-0.17 max=0.20 if [[ $(bc <<< "$percent <= $max && $percent >= -$max") -ge 1 ]]; then echo "...
bc's POSIX spec does not require bare conditionals, and AIX's bc does not support them. You would have to break out the test like this: percent=-0.17 max=0.20 if [[ $(bc <<< "if ($percent <= $max) if ($percent >= -$max) 1") -eq 1 ]]; then echo "Under the $max acceptable buffer: File ACCEPTED" else echo "Over ...
AIX Does not support bc boolean expression [duplicate]
1,416,436,772,000
I have used this to write a function that calculates floating-point numbers. mt (){ echo "$1" | bc -l | awk '{printf "%f", $0}' echo ' ' } This works great, but I was wondering if there is a way to omit the function call entirely taking advantage of the error message that is returned when an operation of floats is a...
Add this somewhere where it would be loaded into your bash environment: (~/.bashrc is one option) (It is a bad idea and won't work for division without spaces, see man page excerpt for why) (The exit is needed only for some non-GAWK AWK versions) command_not_found_handle() { # AWK version, security risk awk "...
Bash as float calculator