date
int64
1,220B
1,719B
question_description
stringlengths
28
29.9k
accepted_answer
stringlengths
12
26.4k
question_title
stringlengths
14
159
1,515,439,233,000
What is the difference between find . and /home/user/* as an input to for command.? For example: for var in $(find .) do echo "$var" done or for var in /home/user/* do echo "$var" done In the first case for command breaks up the file with names containing spaces. While in the second case it does not. Why?
This is standard practice for shells. The order of operations is command substitution ($(find .)), then word splitting, then glob expansion (/home/user/*). From the POSIX standard (word splitting = field splitting; glob expansion = pathname expansion): The order of word expansion shall be as follows: Tilde expansio...
what is the difference between `find .` and /home/user/* as an input to for command
1,515,439,233,000
I want to use my script on many files sometimes. I used this for the purpose: for etminput in $1 do #process done But this just gives the first input. How can I do the process on every wildcard matches?
If you want to loop over all the arguments to your script, in any Bourne like shell, it's: for i do something with "$i" done You could also do: for i in "$@"; do something with "$i" done but it's longer and not as portable (though is for modern shells). Note that: for i; do something with "$i" done is neither ...
Loop in WildCard as Input of Script
1,515,439,233,000
I have several servers which have several files with deploy date info I need to parse, and get a local copy of the files which are 2 months old or older. #!/bin/bash # split on new line not space # don't want to quote everything # globbing desired IFS=$'\n' servers=( blue red ) parseDate() { grep 'deploy_da...
Everything that can be expanded inside your oldfile=$(...) command substitution is being expanded before you ssh. You need to escape the various internal $() if you want them to run on the remote instead of the local. Anything you want to be evaluated on the remote, needs escaping. Try: oldfile=$( ssh $serve...
SSH for loop: parameter passed to function captured in variable is not expanded
1,515,439,233,000
The code below is an mwe based on a script mwe I've written where I specify flags in what I think is the usual way. But I'm seeing really wierd behavior. If I type mwe -e or mwe -n it thinks there are no arguments and returns no arg. If I type mwe -k or mwe -i it thinks argType is not "-" and returns breakin...
From your question it is not clear what you want ! Anyhow it seems that you want the number corresponding to the last argument #!/bin/bash foo=0; while [[ $# -gt 0 ]]; do case "${1}" in '-n') foo=1; shift ;; '-e') foo=2; shift ;; ...
bash scripts with option flags inconsistent behavior
1,515,439,233,000
I wanted to make a list of similar clear commands clearer to read, so I've made a little terminal loop for what in \ cache \ thumbs \ ; do my template $what:clear; done It works great, however I want to achieve an equivalent of my template cache:clear && my template thumbs:clear Is there a way how to easily a...
You could use set -e: (set -e; for what in \ cache \ thumbs; do my template $what:clear; done) set -e causes the shell to exit when a command exits with a non-zero exit code, and the failure isn’t handled in some other way. In the above, the whole subshell exits if my ... fails, and the subshell’s exit code is ...
Is it possible to use && operator in terminal command template loop?
1,515,439,233,000
I would like to perform the same aggregation operations on each of several bunches of files where each bunch is matched by one glob pattern. What I would not like to do is pipe each file name into the aggregation function separately. My first attempt failed because the file names got globbed in the outer loop, flatten...
This requires a careful use of quotes: for fileglob in '/path/to/bunch*1' '/path/to/bunch*2' ... ; do stat $fileglob | awk [aggregation] done But that may fail on filenames with spaces (or newlines). Better to use this: fileglobs=("/path/to/bunch*1" "/path/to/bunch*2") for aglob in "${fileglobs[@]}" ; do set...
Iterating over glob patterns, not the files in them
1,515,439,233,000
I'm trying to copy a bunch of files with the same name, but in different subdirectories, to a single directory, changing the names to ones based on the paths to the original files. I use a for loop that does what I intend in bash, but behaves very oddly in zsh. Command (linebreaks added for legibility): for f in */Fla...
This is happening because cut is outputting NULL characters in the output. You can't pass a program arguments which contain a null character (see this). In bash this works because bash can't handle NULL characters in strings, and it strips them out. Zsh is a bit more powerful, and it can handle NULL characters. Howeve...
Why does this command to copy files in a for loop work in bash but not in zsh?
1,515,439,233,000
I am trying to read user and server details from file tempo.txt and then check the disk space usage of the file system on that unix account using another script server_disk_space.sh.But I am not able to figure out why while loop is only working for first line and for loop is working fine.Please help me understand this...
Unless you add the -n option to ssh, ssh will read from its standard input, which in the case of the while loop is the tempo.txt file. Alternatively, you can use a different file descriptor to read the tempo.txt file: #! /usr/bin/ksh - while IFS='#' read <&3 -r r1 r2 rest; do apx_server_disk_space.sh "$r2" "$r1" don...
Why the behavior of while loop and for loop is different?
1,515,439,233,000
In the following script, the first for loop executes as expected, but not the second. I do not get any error, it seems that the script just hangs. HOME=/root/mydir DIR=$HOME/var DIRWORK=$HOME/Local for f in $(find $DIR -type f); do lsof -n $f | grep [a-z] > /dev/null if [ $? != 0 ]; then echo "hi" ...
Your script is coded in a dangerous way. First, I assume you are using the Bash shell since you tagged it '/bash' and '/for'. In my answer I will quote this great Bash guide, which is probably the best source to learn Bash from out there. 1) Never use a Command Substitution, of either kind, without quotes. There is a ...
Why won't the for loop execute on directory
1,515,439,233,000
I am trying search for all .mkv files in my current folder, then using mediainfo I want to put the height from its meta data to a variable, but it seems it is failing. This snippet: height=$(mediainfo "input.mkv" | grep -E 'Height'); echo $height; height=${height//[!0-9]/}; echo $height; is working great, it outputs...
You wrote *.{mkv} instead of *.mkv. Therefore the loop will only loop about the one "file" *.{mkv} which does not exist. In this case the output of mediainfo is simply empty. Add something like echo "$file" in your loop to verify.
using the variable "file" obtained from `for "file" in` and pass to another script fails [closed]
1,515,439,233,000
I have a bash script that classifies and retrieves files from a remote server. I have trouble with the classification step, which is based on the file names. I am correctly able to identify the different families of files that are defined by the start of the filenames. Filenames can be: ala-olo_ulu-1602915797.txt ala-...
It's easier if you can use zsh as both the local and remote shell: ssh root@$RMT_IP zsh << EOF set -o extendedglob # for (#c10) for file in ${(qq)BASE_NAME}-[0-9](#c10).${(qq)FILE_EXTENSION}(N); do tar -rf ${(qq)BASE_NAME}.tar \$file --remove-files done EOF [0-9](#c10) matches a sequence of 10 decimal digi...
What appropriate regex for recognizing a variable length file name?
1,515,439,233,000
I created this loop that activate my script only on 1 month (20170301 - 20170331): for ((i = 20170301; i<=20170331; i++)) ; do /home/jul/exp/prod/client/apps/scripts/runCer client-layer-name $i; done but I want it to run on 5 month (between 20170301 -20170831), how can I do that ?
Assuming GNU date is available, you can use this bash/ksh93/zsh script: start=$(date -ud 20170301 "+%s") # start time in epoch time (seconds since Jan. 1st, 1970) end=$(date -ud 20170831 "+%s") # end time for ((i=start; i <= end; i+=86400)); do # 86400 is 24 hours runCerclient-layer-name "$(date -ud "@$i" +%Y%m%...
How run a for loop on 5 month?
1,515,439,233,000
I want to read all java Versions on my system. for i in 'find / -name java 2>/dev/null' do echo $i checking $i -version done I receive an error: find: paths must precede expression: 2>/dev/null Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression] What is the problem...
You're receiving that error from the for loop because your for loop is actually looping over one element -- the string, not the command: "find / -name java 2>/dev/null", so it is running: echo find / -name java 2>/dev/null checking find / -name java 2>/dev/null -version ... which is where find's error arises. You mig...
Using for loop with find command
1,515,439,233,000
I am teaching myself bash scripting with the book 'Learning the Bash Shell' by Newbam. I'm getting on OK with the book, but am a bit confused by the following script. It is a script which uses a for loop to go through the directories in $PATH, and print out information about them. The script is IFS=: for dir in $PATH...
The -z test is testing for a zero-length value in $dir, not for anything related to an actual directory. That condition is triggered if you have a :: sequence in your PATH variable, at which point we set the value of the $dir variable to ., meaning the current directory, and we then conduct the standard two tests on i...
Help with bash script
1,515,439,233,000
I want to recursively convert files from .docx to .doc in a folder. The problem is that all the output files are created in the folder where I run the following command, not in the location of the source files: find -type f -name "*.docx"-exec libreoffice --convert-to doc {} \; I understand that find gives source fil...
That's what -execdir is for, if your find supports it. The default find on Linux systems, GNU find, does have it. From man find: -execdir command ; -execdir command {} + Like -exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you s...
execute a command recursively on the files of a folder in the matching location, not in the original one
1,515,439,233,000
I wanted to extract specific lines from multiple bam (a binary file format) files. I can select the lines from a single bam file using this command: samtools view -c TCGA-BH-A0BW-11A.sorted.bam "5:13744354-13744380" 550 I have a directory with 100 bam files like below: TCGA-AC-A2FB-11A.sorted.bam TCGA-AC-A2FF-11A.sor...
If you are using bash, you can iterate over all files with the appropriate extension, and process them as follows: for file in *.sorted.bam do key="${file%.sorted.bam}" value="$(samtools view -c "$file" "5:13744354-13744380")" echo "$key $value" done > output.txt In the loop, we generate the file key by ...
How to create a new file based on results from multiple files and keep the filenames as first column?
1,515,439,233,000
I started a for loop in an interactive bash session. For this question we can assume the loop was something like for i in dir/*; do program "$i" done > log The command takes a lot longer than expected and still runs. How can I see the current progress of the running for loop. Non-Solutions: Look at log. Doesn't ...
Wildcards as dir/* always expand in the same order. This feature together with the current value of $i can be used to show a progress information. The current value of $i can be retrieved by looking at the processes running on your system. The following command prints the currently running instance of program and its ...
Show progress of a for loop after it was started
1,515,439,233,000
I want to define the function cpfromserver in bash so that when I run $ cpfromserver xxx yyy zzz the result is the same as if I had typed $ scp [email protected]:"/some/location/xxx/xxx.txt /some/location/xxx/xxx.pdf /some/location/yyy/yyy.txt /some/location/yyy/yyy.pdf /some/location/zzz/zzz.txt /some/location/zzz/z...
Try this way: cpfromserver () { files='' for x in "$@" do files="$files /some/location/$x/$x.txt /some/location/$x/$x.pdf" done scp [email protected]:"$files" /somewhere/else/ } Important caveat from comments: "It's worth noting for posterity that this solution definitely won't work for co...
Write bash function which operates on list of filenames
1,515,439,233,000
Within my parent_directory, I have subdirectories labeled E-11_G, and E-10_G. Within each of those subdirectories, I have more subdirectories labeled E-2_U, E-1_U, and E0_U. In each of those folders, I'm performing commands on these files: ander, ander.band, ander.data, ander.in, and ander.log. Here's a better picture...
cd parent_directory/ for i in {-11..-10} do for j in -2 0 do ( cd "E${i}_G/E${j}_U/" ls -l ander ander.band ander.data cat ander.in cat ander.log pwd ) done done Notes: You can loop over a range of numbers by using the braces notation: for i in {-11..-10} You can...
How do I perform the same set of commands within multiple subdirectories, in a numerical order?
1,515,439,233,000
I'm currently refactoring a script which has slowly grown beyond control. I'm trying to spin off repetition into functions. However, I have a repeated test being called from a loop, and want it to return continue. Shellcheck says SC2104: In functions, use `return` instead of `continue`. And the shellcheck wiki says d...
You can use 'return` with a parameter for example like the following, #!/bin/bash AFunction () { if [[ "${RED}" -lt 3 ]]; then echo "cont" return 1 else echo "nope" return 0 fi } for i in 1 2 3 4 5 do RED=${i} if AFunction then echo ${i} fi done
Return "continue" from function called from loop
1,515,439,233,000
I have found this error alongside couple more. I believe that the nesting is not quite all right or the for is not correctly indented or without some semicolon. Either way I have tried for quite some time to figure it out, but to no avail. Here is the code: if [ "${runcmd}" != "echo" ]; then statusmsg "Kernels built f...
The var=value cmd ar1 syntax doesn't quite seem to work if cmd is a for loop (in neither bash nor sh). Both sh and bash give syntax errors for: foo=bar for f in ${foo:-BAR}; do echo $f; done which is what you're esentially doing. ( sh: 1: for: not found bash: syntax error near unexpected token `do' ) And that erro...
Shell script - Couldn't find 'fi' for this 'if'
1,515,439,233,000
My aim is to find $files on some $devices and save them to one or more folders which are namend corresponding to a timestamp of each file. To get the timestamp I wanted to use stat. In contrast to echo "$files", stat doesn't process each file separately. Instead it seems to process all files at once when I use "". Do ...
The problem is not with stat but with the source data in your for loop; because you have enclosed it all in quotes it becomes one long single entity. To fix this, remove the quotes around it, thus: for files in $(find /media/*/$devices -iname "*.jpg"); It works provided that none of the files or paths have spaces. Bu...
get timestamp of files presented by FOR loop
1,515,439,233,000
How do I iterate for nth file in a for loop in unix? below some code I have tried but not succeeded #!/bin/bash # n=2 array=( "CTL_MLPOSDTLP1_1.ctl" "CTL_MLPOSDTLP1_2.ctl" "CTL_MLPOSDTLP1_3.ctl" ) for x in "${array[@]}" for ((x=${array[@]}; x<=n; x++)); do echo "array[x]" done
Here are two ways to loop over an array: #!/bin/bash array=( "CTL_MLPOSDTLP1_1.ctl" "CTL_MLPOSDTLP1_2.ctl" "CTL_MLPOSDTLP1_3.ctl" ) echo Loop 1 for x in "${array[@]}" do echo "$x" done echo Loop 2 for ((x=0; x<${#array[@]}; x++)); do echo "${array[x]}" done Looping over selected items This scripts allows yo...
for loop to iterate through some file nth position
1,515,439,233,000
I have a 3 column text file (XYZ coordinates) and I need to iteratively add constants to the first column while appending to the end of the original file. I have tried several options but this is the one that gives the clearest idea of what I'm trying to do: awk ' { for ( i=-4; i<=4; i+=2 ) $1+=i }' coords.txt >> new_...
I think this may be one of the (rare) cases when it actually makes sense to put the loop outside of Awk: $ for ((i=-4;i<=4;i+=2)); do awk -v i="$i" '{$1+=i} 1' Input; done 0 5 6 3 8 9 2 5 6 5 8 9 4 5 6 7 8 9 6 5 6 9 8 9 8 5 6 11 8 9 Otherwise: $ awk '{a[NR] = $1; b[NR] = $2 FS $3} END{for(i=-4;i<=4;i+=2){for(j=1;j<=N...
Iteratively adding value to column of text file
1,515,439,233,000
Simple question: if I have a for loop (zsh) over an unreliable list, by which I mean the list contains entries that can't be predicted beforehand, then can I reset the for loop counter? This demonstrates what I'm asking for: # e.g. list=(1 5 2 9) for i in $list ; do [[ $i = 2 ]] && i=${list[1]} done (This example...
You could do something like: alias forever='while ((1))' \ try-again='continue 2' \ ok-done='break' forever { for i ("$list[@]") { (( i == 2 )) && try-again } ok-done } Note that you need "$list[@]" instead of $list if you don't want to omit the empty elements. Not a lot more legible than:...
reset for loop counter
1,515,439,233,000
I want to create a large number of folders and do some operations in them. The folder names are based on permutations of several chemical elements which I define as variables in a for loop: for Element in Cr Hf Mo Nb Ta Ti V W Zr I want a folder for all permutations of 4 of the elements in alphabetical order, so that...
Spend a couple steps on skipping redundancies. It'll speed up the process overall. declare -a lst=( Cr Hf Mo Nb Ta Ti V W Zr ) # make an array for a in ${lst[@]} # for each element do for b in ${lst[@]:1} # for each but the 1st do [[ "$b" > "$a" ]] || continue # ...
Force alphabetical order in for loop with if conditions
1,634,614,391,000
This is syntactically correct: for f in *bw;do echo $f;done But How would I add an extension to loop through one or the other? The following doesn't work: for f in *bw|*txt;do echo $f;done And this doesn't work either: for f in *bw or *txt;do echo $f;done
In Bash, with shopt -s extglob, and also zsh with KSH_GLOB enabled: for f in *.@(bw|txt) Note that in bash, if there are no matches, the loop will run with $f set to the literal string *.@(bw|txt). To avoid this, in bash: shopt -s nullglob for f in *.@(bw|txt) In zsh, by default, you'll get an error if there are no ...
loop through one file extension or the other in bash or zsh
1,634,614,391,000
I want to read a number of strings from command line and read all strings in a loo. How to process (like Print) them in a loop, further. Sorry I am a newbie, please excuse my novice question. #!/usr/bin/bash echo "Enter the number of names of students" read classcount for ((i=1;i<=classcount;i++)); do read name...
Apart from various ways to improve the data input as shown in the other answer, a small change will make your script work as intended. In the line echo $names[${i}] the shell will expand $names and ${i}, probably resulting in [1] [2] etc, provided that names is not defined. Otherwise it will prepend the value of nam...
How to read variable number of variables in bash
1,634,614,391,000
I have a bunch of folders which are labelled in this way: conf1 conf2 ... But the order in the home directory is like conf1 conf10 conf100 conf101 ... conf2 conf20 conf200 conf201 ... Because each folder contains a file named "distance.txt", I would like to be able to print the content of the distance.t...
For such a relatively small set of folders you could use a numerical loop for n in {1..272} do d="conf$n" test-d "$d" && cat "$d/distance.txt" >> /path/to/folder/d.txt done
Iterating through folders in numerical order
1,634,614,391,000
Please review these codes that are aimed to do basically the same task (finding the main .htaccess of the site and changing it): for dir in "$HOME"/public_html/*.{com,co.il}/; do if pushd "$dir"; then chmod 644 .htaccess popd fi done 2>/dev/null and: find "$HOME"/public_html/*.{com,co.il} -name ".ht...
Indeed, the first loop only considers files in the immediate directory structure you've listed (with the wildcards filled in, of course). The find command that you've listed does not restrict itself to any level of directory structure, and would run chmod on any and all files named .htaccess in the directory tree. To ...
Ensuring that subdirectories won't be affected by a loop (or by find)
1,634,614,391,000
I have to make a script on Ubuntu, which will rename all of files in specified by path directory to be uppercase. I've already found a loop which will rename files, but I'm not sure how I can pass a path to this loop. Can you help me? Here's the loop: for f in *; do mv "$f" "$f.tmp"; mv "$f.tmp" "`echo $f | ...
I suspect you did something like for f in /path/to/dir* instead of /path/to/dir/*. The former will look for files and directories in /path/to whose name starts with dir while the latter will iterate over the contents of the direrctory. In any case, that wouldn't help you because the tr command you are using would chan...
Script which will rename all files in specified by path directory
1,634,614,391,000
The default variable for loops in Perl is $_. Is there any equivalent of this in Bash?
There's no such thing in Bash. Perl is specific in the way that it's been created by a linguist, Larry Wall, and it has the natural language's smoothness built in on purpose. Bash in this respect is dumb. But on a higher level, the pipelines are a sort of loops that operate on default objects. These are not represente...
Default variables in Bash
1,634,614,391,000
I have the following shell code: for value in 10 5 27 33 14 25 do echo $value done But what if I want to manipulate the output later? I want to store the entire output in one variable. Is this possible?
It's no different with for loops than with any other commands, you'd use command substitution: variable=$( for value in 10 5 27 33 14 25 do echo "$value" done ) Would store the whole output minus the last newline character added by the last echo as a string into the scalar $variable variable. You'd then do...
How to Store the Output of a for Loop to a Variable
1,634,614,391,000
I want to run a bash numeric 'for' loop but I want to skip some numbers in between. Example: for num in {1..4, 7..11, 23..34}; do (echo num $num); done or for num in {17..24, 41..48}; do (echo num $num); done Is this possible? How?
for num in {17..24} {41..48}; do (echo num $num); done , and see the documentation for Brace Expansion in bash.
bash for loop multiple number ranges
1,634,614,391,000
Suppose I have a folder which contains a lot of audio files. How can I write a for loop so that for each file audioname.mp3 in the folder, these commads are run: convert -size 300x200 xc:lightblue -font Bookman-DemiItalic -pointsize 40 -fill blue -gravity center -draw "text 0,0 'audioname'" audioname.png ffmpeg ...
for file in ~/Main_dir/*.mp3; do convert -background lightblue -size 300x200 -fill blue -pointsize 40 -gravity center label:"$(basename "$file" .mp3)" "${file%.*}.png"; avconv -i "${file%.*}.png" -i "${file%.*}.mp3" "${file%.*}.flv"; done for the discription of first convert command see my answer on AskUbunt...
for loop for running a command for all files in a folder
1,634,614,391,000
How can I mimic the tree command and iterate through all the files and subdirectories of a directory and echo all the file names? I thought that a subdirectory within a directory is still counted as a directory, so I did: for FILE in *; do if [ -d $FILE ] then echo "$FILE is a directory"; else echo "$FILE is a file" f...
Here's an equivalent to terdon's shell function implemented as a find command: find . -exec sh -c 'for f; do [ -d "$f" ] && is_dir="" || is_dir="not " printf "\"%s\" is %sa directory\n" "$f" "$is_dir" done' sh {} + Or with find & perl (indenting two spac...
How to loop through all the files in a directory and print all the file names, like the command tree
1,634,614,391,000
folks- I'm a bit stumped, on this one. I'm trying to write a bash script that will use csplit to take multiple input files and split them according to the same pattern. (For context: I have multiple TeX files with questions in them, separated by the \question command. I want to extract each question into their own fil...
The csplit command has no saved context (and nor should it), so it always starts its counting from 1. There's no way to fix this, but you could maintain your own counted value that you interpolate into the prefix string. Alternatively, try replacing read -ep "Type the directory and/or name of the file needed to split....
csplit multiple files into multiple files
1,634,614,391,000
I try to generate a command line for a backup script on bash shell. Simple example: EXCLUDES="/home/*/.cache/* /var/cache/* /var/tmp/* /var/lib/lxcfs/cgroup/*"; for FOLDER in $EXCLUDES; do printf -- '--exclude %b\n' "$FOLDER" ; done Should result in: --exclude '/home/*/.cache/*' --exclude '/var/cache/*' --exclude '/...
Whenever you have to specify a list of pathnames or pathnames with filename globs, or just generally a list that you are intending to loop over and/or use as a list of arguments to some command, use an array. If you don't use an array but a string, you will not be able to process things with spaces in them (because yo...
for loop folder list without expansion
1,634,614,391,000
Background I'm running a larger one-line command. It is unexpectedly outputting (twice per iteration) the following: __bp_preexec_invoke_exec "$_" Here is the pared down command (removed other activity in loop): for i in `seq 1 3`; do sleep .1 ; done note: after i have played with this a few times it inexplicably s...
Seems like __bp_preexec_invoke_exec is part of https://github.com/rcaloras/bash-preexec/blob/master/bash-preexec.sh. And it seems like that there is a bug in that script. That project adds 'preexec' functionality to bash by adding DEBUG trap, I did not test, but I can imagine that it might not work properly in the way...
Bash `sleep` outputs __bp_preexec_invoke_exec
1,634,614,391,000
I'm trying to put together what I guess could be called a bash script (not that my bash-scripting abilities are anything to brag about). What I'm trying to do is feed a line from a text file--a text file whose content changes on a regular basis--to a program I'm invoking (imagemagick). It's so far working, but only if...
I guess you are trying to render some text using Imagemagick. If so, why not say convert -background lightblue -fill blue -font Helvetica -size 160x label:"$(<input.txt)" output.gif where input.txt is the file you want to render.
bash script that incorporates content from a file as part of a command
1,634,614,391,000
I am trying to remove large amount of mails (mostly mail delivery failed) from my server using rm -rf /home/*/mail/new/* And I am getting -bash: /usr/bin/rm: Argument list too long I tried using find find /home/*/mail/new/ -mindepth 1 -delete But after 20 minutes it looks like it's not doing anything. How do I use ...
The problem is that /home/*/mail/new/* expands to too many file names. The simplest solution is to delete the directory instead: rm -rf /home/*/mail/new/ Alternatively, use your find command. It should work, it will just be slower. Or, if you need the new directories use a loop to find them, delete and recreate them...
Remove everything within directory using for loop
1,634,614,391,000
I'm trying to loop a file using a delimiter with a ',' and the print out those values in a "list" but I'm not sure how to get all the values of delimiter. I have a file with emails like this (all in one line): [email protected],[email protected],[email protected] and my script is like this: EmailsFile="/dev/fs/C/Users...
A solution is: awk '{ gsub(",","\n"); print $0 }' $EmailsFile
How to loop a line of values using ',' and the print it as a list
1,634,614,391,000
I just wanted to brute-force my old router but the for-loop was really amateur style. How to write a nice for-loop, if I only know the charaters included? Found already that page but it does not include my case. I though of something like the following, but obviously it does not work: for word in $(cat charList)$(cat ...
Brace expansion: Only consecutive characters are allowed Hirachical for-loops: This is a waste of cmd-lines I think I got a nice way: Use eval and brace expansion $ cat charList a,b,_,X,5,1,' ',-,')',3 $ eval echo "{$(cat charList)}{$(cat charList)}{$(cat charList)}" Unfortunately I have no bash now, but this should ...
Using for loop to brute-force a password
1,634,614,391,000
I have many directories and I want to zip them all. $ mkdir -p one two three $ touch one/one.txt two/two.txt three/three.txt $ ls -F one/ three/ two/ I use zip and it works as intended: $ zip -r one.zip one adding: one/ (stored 0%) adding: one/one.txt (stored 0%) $ ls -F one/ one.zip three/ two/ But when I ...
You can see it in your output: for dir in */; do for> echo "$dir"; for> zip -r "$dir.zip" "$dir"; for> done one/ [ . . . ] Since you are doing for dir in */, the variable includes the trailing slash. So your $dir isn't one, it is one/. Therefore, when you run zip -r "$dir.zip" "$dir";, you are running this: zip...
zip outputs in the wrong place when used in a loop
1,634,614,391,000
So I'm creating a function that does a for loop in all the files in a directory as a given argument and prints out all the files and directories: #!/bin/bash List () { for item in $1 do echo "$item" done } List ~/* However when I run the script it only prints out the first fi...
If you're trying to iterate over files in a directory you need to glob the directory like so: #!/bin/bash List () { for item in "${1}/"* do echo "$item" done } Then call it like: $ list ~ Alternatively, if you want to pass multiple files as arguments you can write your for loop like ...
For loop not working in a function with arguments
1,634,614,391,000
I have a set of files in a structure like so; regions ├── ap-northeast-1 │   └── sg-66497903 │   ├── sg-66497903-2017-10-03-Tue-12.39.json │   ├── sg-66497903-2017-10-03-Tue-12.42.json │   ├── sg-66497903-2017-10-03-Tue-12.49.json │   ├── sg-66497903-2017-10-03-Tue-12.53.json │   └── sg-66497903-20...
It's a lot easier in zsh: for sg in ~/region/ap-*/sg-*(/); do files=($sg/sg-*.json(N.Om)) # list of json regular files sorted # from oldest to newest if (($#files >= 2)); then oldest=$files[1] files[1]=() for file in $files; do cmp -s $oldest $file || printf ...
list oldest file in directories in a loop
1,634,614,391,000
I am working on an undergraduate research project that is heavy in bioinformatics, and I am going down a pipeline of file processing. Some background: I am working with shotgun metagenomic data which is very large swatches of A,T,G,C (nucleotides in a DNA sample), and from what I gather, some qualifiers. I have gone t...
Try something like this: for forward_read_file in *_1*.fastq; do srr=$(echo "$forward_read_file" | cut -d_ -f1) rrf_array=( $(find . -name "${srr}_2_*.fastq") ) case "${#rrf_array[@]}" in 0) echo "Warning: No reverse read file found for $forward_read_file" > /dev/stderr ;; 1) reverse_read_file="${...
How to remove four random characters before the .extension from various files using a for loop?
1,634,614,391,000
I am trying to write a script that takes two files as arguments and changes an .svg file with values from a .csv file. Csv file consists of lines with two values; id,colour. I need to find the id in the svg file and add the colour to the line where id matches I don't know if my problem is the sed part, since it gets c...
You shouldn't need to read the CSV into variables, you can just loop on the CSV directly: cat data.csv | while IFS=, read id colour; do # something with $id and $colour Doing var=$(echo text) is kind of redundant - you should just use var="text" directly. I'm not sure what you mean by the construct [ "grep -E..." ...
Changing a file with values from another file - Bash script
1,634,614,391,000
I have a file, 4.txt that contains full paths to *.cfg files as well as additional data I need to strip for the final report (5.csv). For example /source/EDDG/env1/dom1/proj/config/test.cfg <ListVariable name="selected_lookups"> <CompoundVariableValue> <StringVariableValue name="lookup_name" value="CUSTO...
How about this. Single run of awk, so likely quite fast in comparison to the original script. $ awk -F/ 'BEGIN{print "DOM, PROJ, CFG, LOOKUP NAME VALUE(s)"}/source\/EDDG/{a=$2", "$3", "substr($8,0,length($8)-2)", "}/lookup_name/{gsub(/^.*value="/,"");gsub(/".*/,"");print a$0}' 4.txt DOM, PROJ, CFG, LO...
Populate a CSV file from data file with nested loops in bash
1,634,614,391,000
I am running Ubuntu 18.04. I have a directory full of storyboard images in .jpg format as below. image-0000.jpg image-0001.jpg image-0002.jpg image-0003.jpg image-0004.jpg . . image-3898.jpg image-3899.jpg Merging 13 images vertically gives me a Single page. So I think I need to use below command, using a range of 13...
With zsh: #! /bin/zsh - typeset -Z3 page files=(image-<0-3900>.jpg) for ((page = 1; $#files; page++)) { convert $files[1,13] -append ./Merged/page_$page.jpg files[1,13]=() } Note that since there are 3901 images (13 × 300 + 1), the last page will have only one image. You can do something similar with bash like: ...
I need to create a loop in bash to join images vertically and ouput multiple joined Pages for print
1,634,614,391,000
Quick question: I have to write a simple script and part of it is adding up every value in a column -> sum of every column and everything. So file 1 2 5 1 2 1 should return column1: 3 column2: 4 column3: 5 sum: 12 My code is almost perfect but columns are not displayed in ascending order if [[ $# -eq 0 ]]; then aw...
for (variable in array) shall iterate, assigning each index of array to variable in an unspecified order. Solution if [[ $# -eq 0 ]]; then awk '(NF>m){m=NF}{for(i=1;i<=NF;i++)sum[i]+=$i}END{for(i=1;i<=m;i++)print("column "i" : "sum[i])}' file.txt awk '{for(i=1;i<=NF;i++)sum+=$i}END{print("sum: "sum)}' file.tx...
for loop executes in a weird way
1,634,614,391,000
I have a bash script which downloads images from Google Images. This is the command I use: bash getimages.sh 3 rocky%20mountains That command will download the 3rd picture in Google Images. To download the first 10 pictures of the Rocky Mountains in Google Image Search I use the following amateurish command: bash get...
Why do you want to incorporate it in the script when you can run the command in loop itself: for i in `seq 1 20`; do ./getimages.sh $i rocky%20mountains ; done; However, if you really do want to incorporate, a quick way is to move the main script code inside another function and write a for loop to invoke that funct...
For Loop for Google Image Downloading Bash Script
1,634,614,391,000
I have a array like this "Apple Banana Clementine Date" I have to print like this: 1. Apple 2. Banana 3. Clementine 4. Date Script file: for i in "${fruits[@]}"; do echo "$lineno. $i " lineno+=1 done output of myscript: 1. Apple Banana Clem.... I don't understand wh...
The problem is your array. It seems that you have created an array with only one element. Try this example: array=("$(printf 'Apple\nBanana\nClementine\nDate')") for ((i = 0; i < ${#array[@]}; i++)); do printf '%d. %s\n' $((i+1)) "${array[$i]}" done j=0 for e in "${array[@]}"; do j=$((j+1)) printf '%d. %s\n' "...
for loop not working for multiple lines
1,634,614,391,000
How can I get reasonable parallelisation on multi-core nodes without saturating resources? As in many other similar questions, the question is really how to learn to tweak GNU Parallel to get reasonable performance. In the following example, I can't get to run processes in parallel without saturating resources or ever...
To debug this I will suggest you first run this with something simpler than gdalmerge_and_clean. Try: seq 100 | parallel 'seq {} 100000000 | gzip | wc -c' Does this correctly run one job per CPU thread? seq 100 | parallel -j 95% 'seq {} 100000000 | gzip | wc -c' Does this correctly run 19 jobs for every 20 CPU threa...
GNU Parallel with -j -N still uses one CPU
1,634,614,391,000
Basically, I want to see how much time every user spent logged in. (username) pts/0 (IP adress) Tue Dec 12 17:51 - 18:14 (00:22) - this is how one line looks in the last command. The username is between characters 1-9, the time is between 67-71. There are multiple logins from each user, so I want to sum the...
You could use the ac command for this. Part of the psacct package. $ last|head steve pts/0 cpc79909-stkp12- Tue Nov 20 18:40 still logged in steve pts/0 cpc79909-stkp12- Mon Nov 19 22:19 - 23:09 (00:50) steve pts/0 cpc79909-stkp12- Wed Nov 14 19:36 - 19:45 (00:09) steve pts/0 ...
How can I sum the time based on usernames?
1,634,614,391,000
For each line of access.log with the pattern /mypattern: www.example.com:80 192.0.2.17 - - [29/Sep/2017:13:49:02 +0200] "GET /mypattern?foo=bar&iptosearch=198.51.100.5 I would like to extract the iptosearch parameter, and show all the lines of access.log that have this IP and which contains blah. Example: [29/Sep/...
Extended bash + grep + awk approach: Sample access.log content: www.example3.com:80 198.51.100.5 - - [27/Sep/2017:00:00:00 +0200] "GET /hello/blah" ... www.example2.com:80 198.51.100.5 - - [25/Sep/2017:00:00:00 +0200] "GET /blah.html" ... [29/Sep/2017:13:49:02 +0200] "GET /mypattern?foo=bar&iptosearch=198.51.100.5: w...
Extract all the traffic corresponding to a request with a parameter
1,634,614,391,000
I am trying to create a bash function which should kill all processes using some ports specified in port_array. The kill-port function works if I call it myself with a port e.g. with kill-port "80";. But if I call it inside the for loop I get some strange error from kill: Usage: kill [options] <pid> [...] Options: <p...
There is a solution, thanks to @StéphaneChazelas comment: "Just do: lsof -ti "tcp:$1" | xargs -r kill, that's what -t is for (and -r tells xargs not to run the command if there's no argument. That's for GNU xargs. Some other implementations like FreeBSD do that automatically)" In the end it looks like this and also ...
Bash | port killing loop fails
1,634,614,391,000
I am trying to use awk to manipulate data.I have a data file with two columns and I would like to find the row that contains an specific value. But there is more than one row that contains this value and I only would like to find the first one. I tried it with a for-loop and break but it does not work the way I expect...
Now I have a working solution BEGIN { SearchMinFlag = 0; TempLimit = 195.0 DeltaTime = 550 TempMin = "LEER" FS = "\t" } # Stop MinSearch NR > 2 && $1 > tstop {SearchMinFlag = 0} # MinSearch SearchMinFlag == 1 { ywert = $2; if (ywert < TempMin) { TempMin = ywert; TimeMin = ...
awk: for-loop with break option
1,635,625,585,000
I have two files with two different values. I want to run a command in loop which needs input from both file. Let me give the example to make it simple. File1 contents: google yahoo File2 contents: mail messenger I need output like the below google is good in mail yahoo is good in messenger How can I use ...
The standard procedure (in Bash) is to read from different file descriptors with the -u switch of read: while IFS= read -r -u3 l1 && IFS= read -r -u4 l2; do printf '%s is good in %s\n' "$l1" "$l2" done 3<file1 4<file2
Parse two files input in for/while loop
1,635,625,585,000
Is it possible to use a for-loop with the watch command? I'm not really sure what to make of this error with what I've tried: $ for i in 1 2 3; do echo $i; done 1 2 3 $ watch -n 10 for i in 1 2 3; do echo $i; done -bash: syntax error near unexpected token `do' $ watch for i in 1 2 3; do echo $i; done -bash: syntax err...
watch's command argument(s) are a script that is run with sh -c. If the command arguments are just a list of tokens separated by spaces (e.g. watch ls -l), it concatenates them all and runs them. But unquoted shell meta-characters are used by the shell that you run watch from and are never seen by watch. This means ...
How to watch a for-loop in bash?
1,635,625,585,000
I need to rename some files using a loop but I can't get it to work as I am still very new at Linux. the files that need to be renamed are: E9-GOWN33_multiplemap.bin.10.fa E9-GOWN33_multiplemap.bin.16.fa E9-GOWN33_multiplemap.bin.21.fa E9-GOWN33_multiplemap.bin.7.fa to a shorter name such as: E9.bin.10.fa E9.b...
If you have perl rename (default on Ubuntu, Debian and many other systems), you can just do rename -n 's/-GOWN33_multiplemap//' ./*fa If that gives you the right file names, run without the -n to actually rename them: rename 's/-GOWN33_multiplemap//' ./*fa
Renaming multiple files using a loop
1,635,625,585,000
I use Ubuntu 16.04 and I execute a list of remote scripts that are in the same directory (a GitHub repository): curl -s https://raw.githubusercontent.com/${user}/${repo}/master/1.sh | tr -d '\r' | bash curl -s https://raw.githubusercontent.com/${user}/${repo}/master/2.sh | tr -d '\r' | bash curl -s https://raw.githubu...
For two or more files you could use Unix seq: for var in $(seq 6) do curl -s https://raw.githubusercontent.com/${user}/${repo}/master/$var.sh | tr -d '\r' | bash done Explanation: Use the output of seq to attain a count up to 6 (as the question lists 6 curl operations). Read the output into the variab...
Execute 2 or more remote scripts sharing the same curl pattern, without redundancy
1,635,625,585,000
This command outputs PID of process listening on port 8083: lsof -i4TCP:8083 -sTCP:LISTEN -t When there is no process, it returns empty string. No process is running on that port so I am checking if that command returns empty string if [[ -z $(lsof -i4TCP:8083 -sTCP:LISTEN -t) ]]; then echo "waiting for startup" e...
[[ … ]] evaluates a conditional expression. In a conditional expression, -z is an operator which takes a string as argument and returns true if the string is empty and false otherwise. In for ((…; …; …)), each of the three semicolon-separated parts inside the double parentheses is an arithmetic expression. In an arith...
Expression evaluates to false in for loop whereas it's true in if
1,635,625,585,000
I have one file query_ids with several lines such as: id1 id2 id3 I'm using grep idx to find matches of the id in my_file. I redirect these matches to a new matches file. I'm also using grep with option -v to obtain all mismatches which I redirect to a mismatches file. I'm using this small script: #!/bin/bash for i...
What you are doing is that you get one ID, say id1, and then you extract all lines matching that ID into matches. Then you extract all lines not matching that into missing. For the next ID, id2, you then add the lines matching that ID to matches, and the lines not matching id2 to missing. Now, missing contains all li...
grep loop: I'm using each line of one file as query to find matches another file. Why is my output inconsistent?
1,635,625,585,000
I have a loop that checks for certain criteria for whether or not to skip to the next iteration (A). I realized that if I invoke a function (skip) that calls continue, it is as if it is called in a sub-process for it does not see the loop (B). Also the proposed workaround that relies on eval-uating a string does not w...
The problem is that when your function is executed, it is no longer inside a loop. It isn't in a subshell, no, but it is also not inside any loop. As far as the function is concerned, it is a self-contained piece of code and has no knowledge of where it was called from. Then, when you run eval "$skip_str" there is no ...
continue: only meaningful in a `for', `while', or `until' loop
1,635,625,585,000
I have a small script which should print a couple of calls to a makefile i got. mylist='$(call list_samples,AON_9,NT_1,SC_17) $(call list_samples,AON_10,NT_2,SC_18) $(call list_samples,AON_11,NT_3,SC_19) $(call list_samples,AON_12,NT_4,SC_20) $(call list_samples,AON_13,NT_5,SC_21) $(call list_samples,AON_14,NT_6,SC_22...
You need to use an array to keep the elements together: mylist=( '$(call list_samples,AON_9,NT_1,SC_17)' '$(call list_samples,AON_10,NT_2,SC_18)' '$(call list_samples,AON_11,NT_3,SC_19)' '$(call list_samples,AON_12,NT_4,SC_20)' '$(call list_samples,AON_13,NT_5,SC_21)' '$(call list_samples,AON_1...
for loop over a list
1,635,625,585,000
When i am using the below syntax to iterate why two brackets are needed ? for (( expr1; expr2; expr3 )) do command1 command2 .. done and the below code doesn't work ? and throws error "syntax error near unexpected token `('" for ( expr1; expr2; expr3 ) do command1 command2 .. done
The reason for this is ( has a different meaning. From the bash manpage: (list) list is executed in a subshell environment (see COMMAND EXECUTION ENVIRONMENT below). Variable assignments and builtin commands that affect the shell's environment do not remain...
For loop brackets - C like syntax
1,635,625,585,000
#!/usr/bin/bash TARGETS=( "81.176.235.2" "81.176.70.2" "78.41.109.7" ) myIPs=( "185.164.100.1" "185.164.100.2" "185.164.100.3" "185.164.100.4" "185.164.100.5" ) for t in "${TARGETS[@]}" do for a in "${myIPs[@]}" do echo "${a} ${t} -p 80" >>log 2>&1 & echo "${a} ${t} -p 443" >>log 2>&1 & ...
I find your question hard to understand: you seem to want both parallel and sequential execution. Do you want this? for t in "${TARGETS[@]}"; do ( for a in "${myIPs[@]}"; do echo "${a} ${t} -p 80" >>log 2>&1 & echo "${a} ${t} -p 443" >>log 2>&1 & wait done ) & done each target's for ...
How might I execute this nested for loop in parallel?
1,635,625,585,000
In this small for loop I created, I need the loop to print this message only once for all arguments. for arg in $@ do echo "There are $(grep "$arg" cis132Students|wc -l) classmates in this list, where $(wc -l cis132Students) is the actual number of classmates." done What contains in $arg is a few names that d...
You don't want to loop through the arguments, this is reading them one at a time causing your echo statement to execute once for each argument. You can do something like the following: #!/bin/sh student_file=cis132Students p=$(echo "$@" | tr ' ' '|') ln=$(wc -l "$student_file") gn=$(grep -cE "$p" "$student_file") ec...
For loop printing echo command only once
1,635,625,585,000
I have a directory with 2000+ text files. I am trying to make a script that: Reads a list of IP addresses from ip.txt Cats each file in the directory Greps each file for the IP address If keyword is found, echoes the keyword and the file name to a file. The output should be like this: $ cat results.txt 192.168.2.3 w...
First, save a cat by not using one when you don't need it. Rather than: cat haystack | grep needle You can simply: grep needle haystack As for your script: > results.txt # start with a fresh file for every run while read ip; do grep "$ip" * | grep -Ev 'results\.txt|ips\.txt' >> results.txt done < ips.txt Th...
How can I grep each file in a directory for a keyword and output the keyword and the filename it was found in?
1,635,625,585,000
I have a file (ordered_names) which is in the format pub 000.html pub.19 001.html for about 300 lines, And I can't find a way to feed this to the mv command. I have read Provide strings stored in a file as a list of arguments to a command?, but I could not get what I came for. Here are some of the attempts I made : f...
Try: while read -r file1 file2; do mv -n -- "$file1" "$file2"; done <inputfile This assumes that the file names on each line in the input file are space-separated. This, of course, only works if the file names themselves do not contain spaces. If they do, then you need a different input format. How it works while ...
How to read multiples arguments per line for a bash command?
1,635,625,585,000
My iTunes library is on a NAS (WD MyCloud 4TB), and I have a number of TV series, organised by iTunes library in the usual: 'TV Shows' folder: TV Show 1 |------------- Series 1 |-----------01 Episode Name.m4v |-----------02 Episode Name.m4v |... |------------- Series 2 ...
Having done something very similar recently I already had a script. for f in */*/* do destdir=${f%/*} tvshow=${f%%/*} season=${destdir#*/} episode=${f##*/} # Get season number seasonnum=${season##* } dest=$(printf "%s/%s - S%02iE%s" "$destdir" "$tvshow" $seasonnum "$episode") echo "mv -- \"$f\" \"$des...
Batch renaming TV Series
1,635,625,585,000
I am using an if condition inside a for loop. If the if condition returns yes, then I'd like to go to the start of the for loop again. Is this possible in bash? #!/bin/bash for i in /apps/incoming/*.sql do j=$(egrep "[A-Z]{6}[ ]{1}[@abc_id]{10}[ ]{1}[=]{1}[ ]{1}[0-9]*" $i | awk '{ print $4 }') #echo $j #Query databas...
If you want to move on to the next query, use the continue statement. If you want to repeat the same query, use a loop. You want to repeat the query, so write a script that does that, rather than disguising your intent with a low-level construct that doesn't even exist in the language you're using. for i in /apps/inco...
Go to the beginning of the loop in bash
1,635,625,585,000
I recently came up with the following one-liner: for f in *.mp3; do sha1sum $f | sed -r 's/[a-z]//g' | cut -c1-2 | awk '{ print ($1 >= 255) ? $1 - $1 + (1/3)*$1 : $1 }' | xargs -i id3v2 -T {} $f; done I needed it because I've got an MP3 player that does not have a shuffle function. It was the only way I could find (i...
If you really don't want to have this in its own file, you should use a bash function, not an alias. How did you define your alias? If you wrote something like alias bla="for f in *.mp3.... your * might be empty, if you did not escape it, because it is interpreted at evaluation-time of your bash, not at the time it ru...
What's the right way to reuse this one-liner?
1,635,625,585,000
I often use a for loop to i.e. convert a bunch of file formats. In some cases, where text transformations or variables occur, it would be nice to check if the substitutions were performed correctly. for i in *; do convert $i ${i%jpg}png; done Is there an easy way to show the performed command? Following the example a...
set -x for file in *jpg; do convert "${file}" "${file%jpg}png" done set +x Setting the -x shell option will display each executed command as it is set to be executed after all parameter expansions are completed. +x undoes this.
Echo contents of for loop automatically
1,635,625,585,000
I'm trying to create a cron job that checks the status of certain worker machines and triggers a webhook: It works, but I'm not sure that this is the best approach: for i in $(oc get nodes | awk 'FNR>1 {print $2}');do if [[ $i != 'Ready' ]];then <TRIGGER_WEBHOOK>;fi;done Output of oc get nodes # oc get nodes NAME ...
The one thing I can see that I might change is removing the if: for i in $(oc get nodes | awk 'FNR > 1 && $2 != "Ready" { print $2 }'); do <TRIGGER API> done
Pipe for loop with awk and if
1,635,625,585,000
I have the following setup: x=0 y=1 z=2 task0(){ for file in "${files_array[$x]}" do sed -i "$var" $file x=$((x+3)) done } task1(){ for file in "${files_array[$y]}" do sed -i "$var" $file y=$((y+3)) done } task2(){ for file in "${files_array[$z]}" do sed -i "$va...
An ordinary for loop iterates over a static unchanging list of items. In each of your three loops, that list consists of exactly one item. For example, in task0, you loop over the single element $x from the list file_array. Instead, you may want to use while loops: task0 () { X=${#file_array[@]} while [ "$x"...
Background for-loop only cycles once
1,635,625,585,000
I am running Mac OS. I have a directory /Users/sethparker/Documents containing several subdirectories /Users/sethparker/Documents/dir1,/Users/sethparker/Documents/dir2,/Users/sethparker/Documents/dir3. Each subdirectory is filled with identically named, tab separated files file1.txt,file2.txt,file3.txt. I would like a...
If you can safely run this for all subdirectories and all files in those subdirectories, all you need is: sed -i "" 's/\t/,/g' /Users/sethparker/Documents/*/*
Converting files in multiple directories from tab separated to comma separated
1,635,625,585,000
I use this code in my scripts to process files inside a folder, but it only works for subfolders. if [ -d "$1" ]; then for file in "${1%/}/"*/*(*.mkv|*.mp4|*.avi); do I know I can just remove /* to work with flat folders, but I'm looking for a more clean way to handle both flat folders ( no subfolders ) and folders...
Try globstar and extglob which is specific to bash #!/usr/bin/env bash shopt -s globstar extglob if [[ -d $1 ]]; then for file in "$1"/**/*.@(mkv|mp4|avi); do : done fi
For loop for subfolders and flat folders at once
1,635,625,585,000
So I am trying to run a program iRep and usually it runs as- iRep -f Bins/10000A-01-01_bin.* -s sam/10000A-01-01.sam.sorted.sam --sort -o 10000A-01-01_iRep_output in sam folder - 10000A-01-01.sam.sorted.sam 10000A-01-02.sam.sorted.sam 10000A-01-03.sam.sorted.sam in Bins folder - 10000A-01-01_bin.1.fa 10000A-01-01_bi...
#!/bin/sh # Loop over the SAM files for sam in sam/*.sam.sorted.sam; do # Extract the sample name by taking the basename of the SAM file # and removing the known filename suffix. sample=$(basename "$sam" .sam.sorted.sam) # Call iRep (as described in the question) iRep -f Bins/"$sample"_bin.* -s "...
Loop to run a program using multiple files from different directories
1,635,625,585,000
I am submitting a job to a computer. It looks something like this: mpirun -np 12 example_S57 -o S57.results -r S57.final mpirun -np 12 example_S58 -o S58.results -r S58.final ... ... ... mpirun -np 12 example_S74 -o S74.results -r S74.final How can I loop through this command and run this for S57 up to...
for example in S{57..74}; do mpirun -np 12 "example_$example" -o "$example.results" -r "$example.final" done This uses a brace expansion in bash to create the Snn values to loop over. The value $example will in each iteration be one of these values and can be used when calling the mpirun command.
looping through command to submit several jobs
1,635,625,585,000
I have a set of files in a directory. And every file will have a line called ---PUBG-xxxxx-- or ---PUBG-xxxxx, PUBG-yyyyy ----. Below is the output of the grep command. grep "^--" FILE*.sql | grep "PUBG" FILE1.sql:---PUBG-10901-- FILE2.sql:---PUBG-11617-- FILE3.sql:---PUBG-11625-- FILE4.sql:--PUBG-11724-- FILE5.sql:...
You wouldn't need to write a loop. You could just pipe your ouput to sed. My attempt is as follows: grep "^--" FILE*.sql | grep "PUBG" | sed -E 's/--+\ ?//g' Which would give FILE1.sql:PUBG-10901 FILE2.sql:PUBG-11617 FILE3.sql:PUBG-11625 FILE4.sql:PUBG-11724 FILE5.sql:PUBG-11720, PUBG-11406 FILE6.sql:PUBG-11403 FILE7...
GREP for pattern and remove all the junk characters before or after the pattern
1,635,625,585,000
PROBLEM: I can't get the $@ variable to do what I want in a for loop, the loop only sends one name into the file while looping, it should loop through all the arguments and write them to the file USERS.txt each on its own line. Here is the file: something78 something79 something7 dagny oli bjarni toti stefan_hlynur je...
The problem is with the incorrect usage of exit 127 in your for loop, which is exiting after the first for-loop iteration. You need to group the echo statement and the exit as a compound block under {..} to prevent this. echo "$user" >> USERS.txt || { echo "writing to USERS.txt failed"; exit 127; } Without this group...
The $@ variable is not working in a for loop, trying to iterate through a users list
1,635,625,585,000
I have roughly 1 million images on a directory. The files were numbered from 1 to n. I am using for loop to iterate over each image. Since each iteration is checked by individuals, only certain number of iterations could be done in a day. When I begin the loop again the subsequent day, the loop obviously begins fr...
If your readfiles.txt contains all already processed files, you can use grep to look up if a certain was done or not. After running the python script, update that file with the processed file. for f in /ImageFolder/*.jpg; do if ! grep -q "$f" readfiles.txt; then python ~/runprog.py --query "$f" echo "$...
Begin for loop every time where it ended last
1,635,625,585,000
I have thousands of *csv files in a certain subdirectory. There's a simple in line executable which I use to work with these files, which I pipe into a new file: executable file1.csv standard.csv > output_file1.csv I would like to create a for loop to do this not just for file1.csv, but for all files in that subdir...
Credit to Bruno9779 for the original draft of this answer. Not sure why it was self-deleted, as it was a pretty good answer: You have pretty much done it yourself: destinationDir="/destination/path/here/" if cd "$destinationDir"; then for file in *.csv; do # run executable on "$file" and output ...
Loop through all files in a given subdirectory, name the output by the looped file
1,635,625,585,000
I've to run a command iptables --flush in 100+ servers. I don't have root credentials, but have sudo access for my account. So I come up with a below script to run the command in all servers. I added the servers names in the flushhosts file. [root@~]# cat testscript.sh > for i in `cat /flushhosts` > > do > > sshpa...
If you are open to a different approach I would like to propose using expect: Create a small expect script ex1.sh #!/usr/bin/expect -f set arg1 [lindex $argv 0] spawn ssh username@$arg1 expect "password: " send "Mypwd\r" expect "$ " send "sudo /sbin/iptables --flush\r" expect "password " send "Mypwd\r" expect "$ " sen...
SSH to servers with sudo access - script throws unexpected end of file error
1,635,625,585,000
Does GNU Parallel start a batch of as many jobs as possible (the number of jobs started being governed by GNU Parallel internals or/and the -j option along with given parameters), and once complete, then start the next batch of jobs and so on? Context I want to learn how to better handle timestamps related to jobs (st...
GNU Parallel starts a job when there is a free job slot. The number of job slots is given by -j/--jobs and defaults to the number of CPU threads. Let us assume your server has 8 CPU threads. When you start GNU Parallel it will spawn 8 jobs immediately. When a job finishes, the info is logged (in --joblog), and a new j...
Understanding timestamps in a GNU Parallel --joblog output
1,635,625,585,000
Trying two variables with a here-document to generate a list of bash scripts. I ran into the problem that I cannot put the two variables into the script properly and the output file (only one file) has the file name of cut_cat.sh, basically the code is interpreted cat as text, not a function. How can I improve this? T...
A lot of this is guesswork since you haven't told us any detail at all, but I think that ${FA_PATH}/R2_adaptor expands to a file name and I think what you are trying to do is iterate over the contents of the file. Which means that what you were probably looking for is for n in $(cat ${FA_PATH}/R2_adaptor). However, a...
Here-document with two variables
1,635,625,585,000
I have a series of files located in a series of folder, for example: ~/BR2_1-3/bin.1.permissive.tsv ~/BR2_1-3/bin.2.permissive.tsv ~/BR2_1-3/bin.3.orig.tsv ~/BR2_2-4/bin.1.strict.tsv ~/BR2_2-4/bin.2.orig.tsv ~/BR2_2-4/bin.3.permissive.tsv ~/BR2_2-4/bin.4.permissive.tsv ~/BR2_3-5/bin.1.permissive.tsv ~/BR2_3-5/bin.2.pe...
find and xargs are typically recommended for this: find "$HOME" -name \*.tsv | xargs awk -F'\t' -v OFS='\t' '$5 != "" {print $1, $5}' >> output.tsv or, more safely find "$HOME" -name \*.tsv -print0 | xargs -0 awk -F'\t' -v OFS='\t' '$5 != "" {print $1, $5}' >> output.tsv find's -print0 directive prints out the m...
Use For loop to extract certain columns from a series of files to write new tab-delimited files
1,635,625,585,000
I'm making a script to start up a number of services at server reboot. To do this, I'm looping over the directory, checking that each has a start.sh script, and calling that script if they do. However, as part of this, I would like to set up the script to ignore a service it has a select name, in this case mongo: fo...
When you iterate over files with a glob the path will be added to the file. So if your file is just mongo (which it should be based on your code, if it is not that is also a problem), your loop will set service to /home/<YOUR USER>/start/mongo. You are then trying to see if that is not equal to mongo which it is not...
How to ignore file in a for loop
1,635,625,585,000
I have a loop in a bash script, test.sh that reads as follows: #!/bin/bash CHOSEN_NQUEUE=0 foo(){ for chunk in $(seq 0 $((${CHOSEN_NQUEUE}-1))); do echo "CHUNK = $(($chunk+1))" done } bar(){ CHOSEN_NQUEUE=10 foo } bar This loop has previously been working fine up till now. If I run the program a...
The error you get indicates that $chunk contains a multiline value, all the numbers from 0 to 9. That would happen if word-splitting doesn't happen on the result of $(seq ...) in the for. Now, the usual way to prevent word-splitting is to put double-quotes around the expansion, so for chunk in "$(seq ...)" wouldn't ex...
(Bash) For Loop Not Functioning Properly
1,635,625,585,000
I have a requirement to perform specific set of tasks based on server , So I want to have the condition(s) defined based on server. Here is the script I came up with and I have read multiple blogs and couldn`t find any mistake from my script. Can you guide on what I am overlooking here ? #!/bin/bash SERVER_NAME=`host...
In shell, spaces matter. Replace: if [$SERVER_NAME == $i] with: if [ "$SERVER_NAME" = "$i" ] Without the spaces, the shell thinks that you want to run a command named [$SERVER_NAME (such as [servr1) with arguments == and $i]. With the space, the shell runs the test command, denoted by [. Also, always place shell va...
If condition on shell not working , not sure what is the mistake I am doing? [duplicate]
1,635,625,585,000
I have 2 text files "${LinkP}" and "${QuestionP}. I want to read these files and store each complete line in the respective array, IFS=$'\r\n' GLOBIGNORE='*' command eval "LinkA=($(cat "${LinkP}"))" IFS=$'\r\n' GLOBIGNORE='*' command eval "QuestionA=($(cat "${QuestionP}"))" Now I want to operate on these using a for...
store each complete line in the respective array is easy with a different approach: mapfile LinkA < "$LinkP" See help mapfile for more options, such as -t to remove a trailing delimiter from each line.
Reading multiple files and operating on stored Arrays
1,635,625,585,000
If a parameter is provided as an input, script should only check number of lines for that input file, otherwise script should display number of lines for each file within that directory. The script file should be ignored i.e. the count for the script file should not be displayed. I tried: #!/bin/bash if [ $# -eq 0 ]...
I think you almost got it. You can use basename "$0" to find the name of the script from within the script, and print the line count of everything except that #!/bin/bash if [ $# -eq 0 ] then for k in * do if [[ ! -d "$k" && "$k" != `basename "$0"` ]] then wc -l "$k" fi ...
Count number of lines in each file within current directory using a for loop?
1,475,657,579,000
I'm having a problem here on a bash script I made. In a for loop, I iterate on all the arguments to construct a string variable that is later fed to an "eval" command: for arg in "$*" do if [ $arg != $lastArg ]; then findTarget+="-name $arg -o " else findTarget=$(echo $f...
The syntax to loop over the positional parameters is for arg do alone. "$*" is the concatenation of the positional parameters with the first character of $IFS, so you would be looping over one element only. Also, if you want to build a list of arguments for the find command, you need an array, not a string. And don't...
Problem with wildcard expansion in for loop range
1,475,657,579,000
I have script here that will list the date that the user will enter and output the date 5 days ago. #!/bin/bash echo "What month?" echo "1 - January" echo "2 - February" echo "3 - March" echo "4 - April" echo "5 - May" echo "6 - June" ...
Use an array instead of trying to create separate variables. declare -a x for dy in {0..4}; do x+=( "$( date -d "$mn $d - $dy days" +'%b %_d' )" ) done You may then access the four values in ${x[0]} through to ${x[3]}. For the first part of your script, have you considered using a select statement? select mn in "J...
Storing the each output into a variable
1,475,657,579,000
Overview: I save my variable in a config file and call them later. Each entry with the name FailOverVM has a number beside it like FailOverVM1 and I want to check to see if it has data and generate a function named FailOverVM1() that later in the script starts $FailOverVM1Name, which happens to be 'Plex Server' I can...
Asides: you can eliminate the wc -l by using grep -c FailoverVM.Name configfile. But if you want to use numbers over 9 decimal (not e.g. 123456789abcdef) your pattern needs to be FailoverVM[0-9][0-9]?Name or FailoverVM[0-9]{1,2}Name in -E extended mode. Also for i $VMCount is a syntax error; I assume you mean for i in...
Func name as variable in loop
1,475,657,579,000
I am new in programing with bash script. Here is my problem: I am going to open a sort of data whose file name includes the date (format: file_yyyymmddhh.nc). There are some requirements: mm is from 01 to 12. This must be a two-digit integer. dd is from 01 to 28, 30, or 31, depending on the what month it is. I tri...
You can use printf to format your numbers. Here the %02d denotes a two digit integer with leading zeros if appropriate. dd=$(printf "%02d" $i) You can extend this so that if $y, $m, $d, and $h contain your year, month, day, and hour numbers the construct could become this file=$(printf "file_%04d%02d%02d%02d.nc" $y $...
Question about if structure and loops
1,475,657,579,000
I have created a script that will create a few directories and then organize other files from one directory by moving them into specific sub-directories based on their extension (i.e. .gif in media, .jpg in pictures). Now I have to check those directories to make sure they contain only those files with the proper exte...
How about you just print all the files that don't match your extensions? find documents -type f ! \( -name \*.txt -o -name \*.doc -o -name \*.docx \) find media -type f ! -name \*.gif find pictures -type f ! \( -name \*.jpg -o -name \*.jpeg \) Why do you need to check other at all if anything is allowed in th...
Check if the files in a specific directory have the proper extension?
1,475,657,579,000
I use SCP a lot to transfer log files from servers to a jumpbox where I can analyse and troubleshoot etc. If I have a cluster of servers and I want to create a set of subdirectories I do it like this: mkdir -p /foo/bar-nnn/{mailserver,dnsserver,minecraftserver,syslogserver} Lets's say 'bar-nnn' is a reference of sort...
Try this: IFS= read -r -p "Folder name: " dir mkdir -p "/foo/${dir}/"{mailserver,dnsserver,minecraftserver,syslogserver}
Create subdirectories under a parent but prompt for the name of the parent