New answers tagged

0

Using any awk in any shell on every Unix box: $ awk -F' -- ' -v OFS='\t' ' { hdr[NR]=$1; n=split($2,v," "); for (i in v) vals[NR,i]=v[i] } END { print hdr[1], hdr[2]; for (i=1; i<=n; i++) print vals[1,i], vals[2,i] } ' file Frequencies IR Inten 1403.6738 25.0809 1403.6738 25.0809 1403.6738 25.0809 and to work for ...


0

With GNU Parallel you would do something like: [compute $script] export script run_one() { i="$1" export server_name=`echo $i` echo "connecting to $i" expect -c "$script" echo "Job completed on $i" echo "-----------------------------------" } export -f run_one cat "$file" | parallel -...


1

In a double-quoted string, command substitutions ($(...)) and variable expansions ($foo) are processed, and the backslash in front of the dollar sign prevents that, removing the backslash. This happens during the assignment PS1="$(...)" or PS1="\$(...)". But the same expansions are also processed when the prompt is printed, so if the ...


1

Use the second form to make things slower. According to perf it takes about 3 million clock cycles to run bash -c 'echo hello' on my machine. It will hopefully take less than this to do the command substitution but it will still be much more than just having the fixed string. If echo was replaced by something that did rather more, perhaps id -u it would ...


0

Using Raku (the programming language formerly known as Perl6) Raku has a nifty Z operator for problems like this, to 'zip up' items, one from each list: ~$ raku -e 'my @array1 = lines(); put ( [Z] @array1[0].words, @array1[1].words).join("\n");' Freq_IR.txt Frequencies IR_Inten -- -- 1403.6738 25.0809 1403.6738 25.0809 1403.6738 25.0809 Note: I ...


0

It should be possible to do this entirely in awk: awk -F':' -v ref_id="C000139-102" '$1=="ID" {if ($2==ref_id) print "Identical"; else print "WRONG"}' /dev/eeprom If, as @user414777 suspects, you are dealing with UTF-16-encoded file, you may have to use cat /dev/eeprom | tr -d '\0' | awk -F':' -v ref_id="C000139-...


0

That feature, called value substitution or valsub by Thorsten Glaser (aka @mirabilos), the maintainer or MirBSD and its shell mksh (derived from pdksh), is specific to mksh. It was committed on May 2nd 2013, and released in version R46 announced the next day on the mksh mailing list. It's written on the back of the ${ body; } form of command substitution (...


4

When I do the same thing under bash, I am able to disable icanon, but I don't notice any change in behaviour. That's because bash turns the canonical mode off when reading commands from the user (in order to be able to implement line editing features not offered by the terminal driver -- like inserting text, moving the cursor left and right with the arrow ...


0

For Ubuntu compatibility, I wrote this, which recalls the script with it's options under bash and returns the same exit code. if [ `readlink /proc/$$/exe` != "/bin/bash" ];then bash $0 $@ exit $? fi echo "Shell: "`readlink /proc/$$/exe`


0

Try this bash script. It assumes your list above is a filename called dirs. It reads through that list and checks if directory exists. If it does an echo to screen and tee into a new file called updatedirs. If it doesn't, it will echo to screen and tee into the same new file, called updatedirs along with a comment. You can change things to echo into a ...


4

In the .bashrc you posted, remove the \w in the lines with PS1 before the $ sign. Depending on what you want, be sure to delete it in either of the two lines (or both) near the if [ "$color_prompt" = yes ]; then. If you want to delete it in both, you can use this: if [ "$color_prompt" = yes ]; then PS1='${debian_chroot:+($...


3

The user foo has a limited shell as indicated by your replies. You can fix it by: (sudo) usermod --shell /bin/bash foo


1

java's --version option seems to be undocumented. The documented one is -version. Try java -v<Tab>. java --v<Tab> should also suggest -version if you enabled approximation in the completion configuration: $ java --vTab Completing corrections -verbose:class -verbose -- print class information -verbose:gc -- print gc information -...


5

Note that you can greatly simplify your awk. The default action if an expression evaluates to true is to print the current line. So this does the same thing: awk -F'|' < filename '$1 == "string"' Anyway, you can use the -v option to pass a variable. So your script can be: #/bin/sh if [ $# -lt 1 ]; then echo "At least one argument is ...


0

Here's an example that will return the first filename found in a directory, recursively, regardless of directory depth and how deep the first file is. dir="/home" filename=$(find "$dir" -type d | awk '{print "find "$0" -type f | head -1"}' | sh | uniq | head -n 1) echo "$filename"


0

Extending nisetama's answer: oneliner with jq jq -s '{ min:min, max:max, sum:add, count:length, avg: (add/length), median: (sort|.[(length/2|floor)]) Example: echo 1 2 3 4 | jq -s '{ min:min, max:max, sum:add, count:length, avg: (add/length), median: (sort|.[(length/2|floor)]) }' Gives you: { "min": 1, "max": 5, "sum": 15, ...


-2

#!/bin/bash echo "enter the letter" read f cat file | perl -pne "s/ /\n/g"| sed -n '/'$f'/p' '


1

You should have your script wait for the less child process, otherwise your script will terminate before it, and less will suddenly find itself outside the foreground process group, not able to read commands from the terminal or restore the terminal settings anymore. Also, in order to prevent less for waiting forever for the end of its input, your script ...


1

test "$(grep -rno 'foo' --include \*.txt|wc -l)" = "$(grep -rno 'bar' --include \*.txt|wc -l)" && echo Yes || echo No or var1=$(grep -rno 'foo' --include \*.txt|wc -l) var2=$(grep -rno 'bar' --include \*.txt|wc -l) test "$var1" = "$var2" && echo Yes || echo No Under shell everything you run may become ...


1

Try just this (without the exec line): for (( i=1; i <= 500; i++ )); do echo "hello world $i"; done | less (update) If you want to include the whole script, you can wrap the script with { ... } #!/bin/bash { # output some text for (( i=1; i <= 500; i++)) do echo "hello world $i"; done # whatever output you want... } | less


0

You can check how many jobs are running and wait until they are finished. Here is a sample script: #!/bin/bash i=0 while [[ $i -lt 50 ]]; do n=$(jobs | grep Running | wc -l) if [[ $n -ge 10 ]]; then echo "waiting for jobs to finish ($n running)" sleep 1 else echo start next $i bash -c "sleep $(( $...


6

You have to indicate that you are using a different separator in sed delete command by prepending a backslash \ before the new separator: sed '\|text|d' file See selecting lines by text matching in GNU Sed manual.


0

$i+=$i":" This doesn't do what you want it to do. Instead, it expands $i in the marked places, and tries to run the result as a command. A shell assignment doesn't take the dollar sign on the left hand side (think of it as taking the value of the variable, here we don't want that, but the location to store in). It should be i+=$i":" ...


0

paste is the right tool for the job. But just for the sake of completeness, here's how to do what you were attempting: k="$(head -n1 names.txt)"; for i in $(tail -n+2 names.txt); do k="$k:$i"; done This produces: $ echo "$k" roger:peter:henry


0

An alternative solution with sed and tr: sed '$!s/$/:/' names.txt | tr -d '\n' Ouputs: roger:peter:henry


4

There is a tool that can do it for you: paste $ paste -sd: names.txt roger:peter:henry


2

echo "$(result)" is trying to execute a command named result courtesy of the $(result) part, hence the error message result: command not found. Try this (untested): #!/usr/bin/env bash result='' while [[ -z "$result" ]]; do echo 'Please enter starting letter of Name' read name if [[ $name == [A-Z] ]] then result=...


0

Please use Google next time. Here's a comprehensive guide on how to configure a network interface in RHEL/CentOS 7: https://phoenixnap.com/kb/configure-centos-network-settings In case you're using Network Manager: nmcli device modify <interface_name> ipv4.address <ip_address> In case you're not using NM: ifconfig <interface> <ip_address&...


2

Your script has several issues. First, you are treating strings as arrays (there's no reason or point in doing for foo in $bar when $bar is just one string). Second, you are reading the file multiple times when all you need to do is read it once. Third, you are not quoting your variables, which means the script will break if the file names can contain ...


4

Since you are using awk to extract fields from your lines, why don't you just let it do all the work? It should have sufficient arithmetic capabilities and converting your script into an AWK script may be easier than fixing it. $ cat example-file.txt John,Rambo,99880,2% Elon,Musk,144000,2% $ awk -v FS=, '{ print $1,$2,sprintf("%i", $3 * $4 / 100) ...


2

The accepted answer is wrong. Bash will also directly source ~/.bashrc whenever it determines that it's being run by sshd, whether it's run interactively or not (1). The way bash determines that is by checking if the SSH_CLIENT or SSH2_CLIENT envvar is set and if the SHLVL envvar is less than 1. Example: $ mkdir -p /tmp/foo; echo echo this sux > /tmp/foo/....


2

To answer the question that is actually asked: None. No other shells have this. As the MirBSD Korn shell changelog tells us, value substitutions were added by Thomas Goirand in 2014 to release 46. No other shell has then or since copied this idea, to my knowledge. Some of them have the thing that value substitutions were derived from, but they do not ...


0

I would use a loop that does non-blocking checks. Something like: #!/bin/sh while [ 1 ]; do if [ $(nc -z server1 1521) ] || [ $(nc -z server2 1521) ]; then break fi sleep 1 # if desired done start_apps.sh This loop will run until either condition is met.


2

The solution is to combine the relevant parts of bin/activate with ~/git-prompt.sh. Here __git_ps1_venv() is a function that wraps __git_ps1() and modifies the first argument of __git_ps1() to include the virtual environment. The PS1 variable should be set to the format of your prompt. ~/.bashrc: ################## # Prompt ################## __git_ps1_venv(...


1

You can use strings in print: awk -F, '$1 ~ /Jimmy Fallon/ {print "Name:" $1, "Phone number" $2}' name.csv


3

Try printf: awk -F, '$1 ~ /Jimmy Fallon/ {printf "Name:%s, Phone Number:%s\n",$1,$2}' name.csv


0

There is a description of how that expansion is supposed to work and is useful in this page However: I fail to see how that substitution is actually useful. This two lines are different only in the additional character |: $ mksh -c ' val=one; echo $val; REPLY=init; thing="${|REPLY=beep; other=tested;}"; echo "thing=$thing&...


2

From man bash: HISTFILESIZE The maximum number of lines contained in the history file. When this variable is assigned a value, the history file is truncated, if necessary, to contain no more than that number of lines by removing the oldest entries. The history file is also truncated to this size ...


1

The ${ cmds;} form of the command substitution of ksh93 runs cmds in the same shell, but otherwise captures the stdout like a regular command substitution. Example: a=1; echo ${ a=2; echo wtf;}; echo $a wtf 2 And the fact that it captures the stdout of the commands is exactly what makes it useful, since you don't have to save the output into some temporary ...


2

You can try this, if I'm not too rusty with bash: for d in */*; do cal "${d#*/}" "${d%/*}" > "${d%/*}/${d#*/}/${d#*/}-${d%/*}-cal.dat" done assuming you are in the directory that has the year folders. Which results in: ├── 2019 │   ├── 01 │   │   └── 01-2019-cal.dat │   ├── 02 │   │   └── 02-2019-cal.dat │   └── 03 │   ...


1

I have done this using Raspberry Pi's used in an embedded product. I remounted the main filesystem read-only and copied the SD-card block device over the network. I doubt that you'd get good results using a system that is actively writing to disk as you clone it - either read-only mounts or filesystem snapshots are probably essential.


-1

Granted you've stopped all the services/daemons like MySQL which continuously update its files, you could do the following: Install the same OS using a minimal configuration into a VM On a source OS: sudo tar -cf /image.tar /bin /boot /etc /lib /lib64 /root /usr /var Copy this tar to your VM Unpack the tar file e.g. into /new Now this part is a little ...


4

If the user is only supposed to choose one of many, I'd just use one variable to hold the choice, dropping the per-option variables. We don't really care about all the combinations anyway, we just want one choice of out of three, and another for "unset/default". So: #!/bin/sh cmd= # empty value for default case "$1" in --...


0

I have never done this, but i would attack this by setting up the filesystem so i can take snapshots of it while it is active (using btrfs or by setting up an lvm), then using the live system to package that snapshot how you would like, and sending it over the network to your computer. I hope this helps!


2

The || and && operators are working fine. There are problems in the way that the script is translated, but, despite repeated requests for logic clarification, none has been offered. I have therefore added to the question based on how I understand the copied script is working. One interesting thing is that a bit of the script not posted in the ...


3

I honestly don't know what you're trying to do with those checks. If you need to check that at least one of those programs is available: programs=(fzf rofi dmenu) available=() for prog in "${programs[@]}"; do location=$(type -P $prog) && available+=("$location") done (( ${#available[@]} == 0 )) && die "none of ${...


0

In bash, you can use the extended patterns inside [[...]]: scale=4 [[ $scale == +([[:digit:]]) ]] || echo "Sorry integers only" # ==> no output scale=4.0 [[ $scale == +([[:digit:]]) ]] || echo "Sorry integers only" # ==> Sorry integers only


14

Using csvgrep from the csvkit package to pull out all records that has a codeRegion value containing the string 01: csvgrep -c codeRegion -m 01 file.csv This is using a proper CSV parser, so there will no issues with newlines or commas in properly quoted fields. The -c option selects the column that we'd like to investigate, by number or by name, and -m ...


9

awk '/^01/||n%2{print;n+=gsub(/"/,"&")}' file For each line, /^01/||n%2 If line begins with 01 or n (initally zero) is odd, print Print it n+=gsub(/"/,"&") increment n by the return value of the gsub function. This replaces every double-quote /"/ with itself "&". That would be pointless, indeed, but ...


1

You can use the t option of the read command. For example; read -t 5 -p "Input within 5 seconds:" data if [[ $data ]] then echo " Your input is $data" else echo " You didn't any input" fi Run script; If no give any input within 5 seconds; #~ bash scr.sh Input within 5 seconds: You didn't any input If give ...


Top 50 recent answers are included