date int64 1,220B 1,719B | question_description stringlengths 28 29.9k | accepted_answer stringlengths 12 26.4k | question_title stringlengths 14 159 |
|---|---|---|---|
1,475,657,579,000 |
I am trying to practice my unix skills, I just learned how to use for file in *.jpg; what it does is select all files with .jpg in the working directory, but I do not want to stop there and I do not want to run my bash script twice
So here is the scenario, I got these files, and I wish is select each one of them, then... |
If you are using bash, you can set the nullglob option:
nullglob
If set, bash allows patterns which match no files (see
Pathname Expansion above) to expand to a null string,
rather than themselves.
To illustrate:
$ ls
test1.dummy test1.jpeg test1.jpg test1.test
$ shopt nullglob
nullglob o... | using `for file in` to select multiple extension names then get the basename of "file" then concatenate an extension name |
1,475,657,579,000 |
I have a gallery folder with images and videos in it named in unwanted format.
I want to make a script that scans through each file in that directory and when it finds an image or a video to rename it in this format: "IMG_20190117_200445.jpg"
Year,Month,Day_Hour,Minute,Second.Extension
And the same with videos but wit... |
Here's a script that I think would do what you ask.
I first define a function that takes an extension and a type (either "IMG" or "VID"), uses find to get all the regular files with that extension, loops over them, uses stat to determine their modification time, date to determine the new filename, and renames them.
Th... | How to make a script to rename images and videos with the date of modification? |
1,475,657,579,000 |
My question is a bit different than:
Create directory using filenames and move the files to its repective folder
Since in the same folder I have two similar copy of each file like:
001.txt and 001(1).txt
.....
100.txt and 100(1).txt
For each two similar copies, create one folder and move both similar copies into one f... |
You're nearly there. What you're missing is that you also need to try to strip the bracketed number from the filename to derive the directory:
#!/bin/sh
for file in *.txt
do
dir="${file%.txt}" # Remove suffix
dir="${dir%(*)}" # Remove bracketed suffix if present
mkdir -p -- "$dir" ... | Create directory using filenames and move the files to its respective folder |
1,475,657,579,000 |
I need to create a script to scan folders in a directory and take the name of each folder, make a .txt file, name it with the name of the folder and put inside that folder.
For example:
A directory that has 3 folders in it named "1" "2" and "3"
I want to create a .txt file in each folder named with the name of that fo... |
Assuming you just want the immediately directories and not all nested sub directories.
The following assumes you are currently in the same directories and the directories you want to loop over
for dir in *; do
[ -d "$dir" ] && touch -- "$dir/$dir.txt"
done
This will loop over every file in the current directory... | How to make a for loop to read directory names with spaces in them? |
1,475,657,579,000 |
I have these variables
a1=0.017
a2=0.2
a3=10.7
a4=20.9
a5=35.4
for ((x=1; x<=5; x++))
do
for i in a${x}
do
echo "Welcome $i times"
done
done
The output must be:
"Welcome 0.017 times"
"Welcome 0.2 times"
"Welcome 10.7 times"
"Welcome 20.9 times"
"Welcome 35.4 times"
But my output now is
Welcome a1 times
Welcome ... |
It’s not hard to accomplish what you asked for:
a1=0.017
a2=0.2
a3=10.7
a4=20.9
a5=35.4
for ((x = 1; x <= 5; x++)); do
var="a${x}"
echo "Welcome ${!var} times"
done
It would have been simpler to make a an array variable, though:
a=(
0.017
0.2
10.7
20.9
35.4
)
for x in "${a[@]}"; do
e... | A variable inside an another variable |
1,475,657,579,000 |
I learned from the following sources:
curl -O: Download a file with curl on Linux / Unix command line
jq: How to urlencode data for curl command?
Multiple files and curl -J: download pdf files from using curl
Condition for loop: Shell: how to use 2 variables with for condition and Unable to download data using curl f... |
The first loop overwrites the value of the variable paths in each iteration. Since you later expect this to be an array, make sure it is created properly:
paths=()
for urlencode in "${context_dirs[@]}"; do
paths+=( "$(jq -nr --arg v "$urlencode" '$v|@uri')" )
done
Alternatively, combine the two loops:
for urlencod... | Using cURL, jq, and declaration and for loop condition, I tried to download multiple files from a GitLab private repo, but it downloaded only one |
1,475,657,579,000 |
I am new to linux and i am writing a bash script...
In the script, I have 2 variables(inside the varibles contents are there). I am trying to pass these 2 varibales in a same for loop and perform some actions.
But when i pass 2 varibles in a same for loop, am getting error.
In the below code. to make it ease I am pas... |
#!/bin/bash
# You said variables get their values from commands, so here
# are stand-ins for those commands:
command_to_get_files(){
echo "2019_06/
2019_07/"
}
command_to_get_filesizes(){
echo "100
200"
}
# I assume the values returned from the commands are whitespace delimited
# Therefore it is easy to use c... | How to pass multiple variable to a for loop as a argument in a bash script? [closed] |
1,475,657,579,000 |
I have a .vcf file of 138 first header lines (starts with #) and the others of data (snp in rows(322045) and patients with some infos in columns(the first 10). I used a script bash to calculate for each row the number of cells in that row that are different (in the initial part) from "0|0":
this is my script
for j in ... |
The reason it isn't working is that you are printing $1 and $2 in the END{} block. The END{} is only run once, after the last line of the input file has been read. So $1 and $2 will always be the 1st and 2nd fields of the last line.
In any case, this is an incredibly inefficient way of parsing a text file. You are re... | Loop rows and columns inside awk to count a specific substring for each cell |
1,475,657,579,000 |
I am trying to automate some make commands. Along with the target we have a variable that is passed to make (corresponding to set of a #ifdef's in code).
The make command looks like this:
make <target> <MYCDEF=val>
val can take multiple values (MYCDEF_VAL1, MYCDEF_VAL2...).
target can also take multiple values like: ... |
With GNU Parallel:
parallel -j1 make -kj {1} MYCDEF={2} :::: <(gawk -f script2 Makefile) <(gawk -f script1 config.h)
-j1 forces GNU Parallel to run the jobs in serial (which is probably what you want given the command you run is make).
| Pipe inputs from more than 1 process |
1,475,657,579,000 |
I'm trying to learn some more Linux, and from experience the best way is to try to bang your head against the wall. So now that I've done a task manually a few times I would like to automate it. This involves making a oneliner to kill some tasks so I can restart them.
At the moment I'm working with the following:
for ... |
Notice that the for loop output is broken apart at the word boundaries, viz., whitespaces/newlines. Whereas what you said you wanted is the whole line to come contained in the $i.
So you need to do these 2 things:
set the input field separator to a newline.
disable the wildcards expansion.
set -f;IFS=$'\n'; for i in ... | Scripting with 'for' and grep/egrep |
1,475,657,579,000 |
I have a bash script that lists all files in a directory:
for file in foo/*; do
echo ${file##*/}
done
It works fine if there are files in the directory, but if there are no files it lists files one directory up.
How can I fix this?
|
If there is nothing in the foo directory, the variable file will get the literal value foo/*. The substitution ${file##*/} will yield the string *, and with echo that will output all names in the current directory.
To fix this in bash, the simplest option would be to set the nullglob shell option with shopt -s nullgl... | Command lists wrong |
1,475,657,579,000 |
I have this repository cloned on my Sabayon machine, what I would like to do is write a script that will change into each directory of this repo (just the top-level directories, not directories inside these directories) and run ./autogen.sh --prefix=/usr && make && sudo make install. I was thinking that maybe this scr... |
I have found that this works:
for i in `find . -maxdepth 1 -type d -exec basename {} \;`
do
pushd $i
./autogen.sh --prefix=/usr && make && sudo make install
popd
done
although, some odd error messages pop out from this, so if anyone has a better answer I will be more than willing to accept it.
| How do I write a script to automatically compile and install all Moksha modules? |
1,475,657,579,000 |
I'm having trouble with this piece of code:
22 for filename in "$( ls "$1" | grep ".*\.flac$" )"; do
23 file_path="$1${filename}"
24 ffmpeg -i "${file_path}" -f ffmetadata $HOME/metadata
Instead of a metadata file on each iteration, I'm getting this error message:
Downloads/Ariel Pin... |
how about
for filepath in "$1/"*.flac
do
ffmpeg -i "${file_path}" -f ...
where
"$1/"*.flac will garantee .flac suffix in the end
be sure to quote "${file_path}"
basename can be found using bn=$(basename "${file_path}")
un flac'ed basename can be found using bnnf=$(basename "${file_path}" .flac)
sample
A >... | BASH: looping through ls [duplicate] |
1,475,657,579,000 |
The following piece of code illustrates my problem
I'm afraid I oversimplified it way too much in the first round.
#!/bin/bash
dogLover=1
catLover=2
for ii in dog cat
do
petLover=${ii}Lover
echo (evaluate $petLover)
done
I want the code to return the numeric values 1 and 2 rather than dog and... |
While what StephaneChazelas said is correct in that you can use eval, as a general practice many people try to stay away from eval.
What you can do for this is to use 'indirect expansion'. It's a bashism that is used when you have a variable that contains the name of another variable. To use it, just prefix the variab... | return the numeric value of a indexed variable rather than its name [duplicate] |
1,475,657,579,000 |
I am trying to write a program which i can reuse for copying content into multiple directories. But for the life of it i cannot figure out why the program does not work and is throwing this error.
I have a file with the names of the folders to which i need to copy.
test1
test2
test3
i am trying to copy a file called ... |
So based on the previous comments i was giving blank values to the 'line' variable. it should have read
while read line; do cp -r ./default.meta "$line"; done < test
| cannot figure out why the file will not copy |
1,475,657,579,000 |
Let's suppose I have the following loop:
for i in {1..3}
do
mkdir $i
done
Since I have many other loops in the main code and I am going to change regularly the size of the sequence, I would like to define the start and end of the loop and use these variables in the for loop(s).
I tried this without success:
start=... |
Variables aren't expanded inside brace expansion. Try this instead:
start=1;
end=10;
for ((i=$start; i<=$end; i++))
do
mkdir "$i"
done
| for loop with indices [duplicate] |
1,475,657,579,000 |
I have a series of directories, all with list.txt in the same format, and I wish to put the results into a single file. I am looking to write a script that will iteratively move through each directory tree, extract a specific column from the list.txt file without surrounding text using the grep/awk pipeline below and... |
You are using i, instead of this use $i in grep command.
And you said that you want to put all of them into single file then the last command should be:
cat >> /home/ubuntu/Project/working/output.txt
Or just:
>> /home/ubuntu/Project/working/output.txt
| For loop to iterate over directory tree extracting results from files of the same name [closed] |
1,475,657,579,000 |
This is my script to install Varnish. I run it each time I raise up a new server environment on a VPS.
cd ~
apt-get update
apt-get install varnish -y
sed -i 's/Listen 80/Listen 8080/g' /etc/apache2/ports.conf
sed -i 's/\*\:80/\*\:8080/g' /etc/apache2/sites-available/000-default.conf
sed -i 's/\*\:80/\*\:8080/g' /etc/a... |
Using a function and GNU Parallel you replace the repetetive section:
cd ~
apt-get update
apt-get install varnish -y
sed -i 's/Listen 80/Listen 8080/g' /etc/apache2/ports.conf
myfunc() {
sed -i 's/\*\:80/\*\:8080/g' /etc/apache2/sites-available/$1 &&
a2ensite $1
}
export -f myfunc
parallel myfunc {/} :::... | How to avoid repeating sed commands when adding sites to Varnish? |
1,475,657,579,000 |
How can I convert 5 pictures at a time followed by a wait,
then the next 5 pictures in a directory, on N pictures.
Here's my code:
#!/bin/bash
for i in *.jpg;
do
xload -update 1 &
convert "${dir}"/*.jpg -flip -set filename:t '%d/%t-change' '%[filename:t].jpg' &
wait
done
|
You could keep a count:
For each file, increment the count
If the count reaches 5, wait and reset the count
Like this:
#!/bin/bash
count=0
for i in *.jpg; do
xload -update 1 &
convert "${dir}/$i" -flip -set filename:t '%d/%t-change' '%[filename:t].jpg' &
((count++))
if [ $count = 5 ]; then
wait... | imagemagick convertion in segments |
1,475,657,579,000 |
I am iterating over indexes which are used to create data file id's. When I create the file name (data_file) and echo it, it prints properly, but when I try to sed that variable into the desired files it only places the first index.
# copy files
cp student_t_sampler.c student_t_sampler_copy.c
cp post_process.py post_p... |
You're producing the student_t_sampler_copy.c from the template student_t_sampler.c at the start of the script and outside the loop that updates the copy, therefore you're only updating the copy in the first iteration of the loop, and all of the other iterations there's nothing else to change. You have to copy the fil... | bash for loop variable not changing |
1,443,969,159,000 |
I am trying to implement a python linter using pylint. But I am getting the score of each python file and also displaying the suggestion to improve the score but I am also looking to terminate the GitHub action job if my pylint score is below 6.0 but currently its not failing my job. I have got a way to exit the code ... |
I used a different way to implement this requirement. Now the GitHub workflow fails if pylint score is less than 6.0 for a single file which is present in my python repo.By using find command in a for loop its able to terminate the job if its returning an exit code corresponding to an error.
- name: Lints each pytho... | Need to capture exit code of pylint command using find in Github actions |
1,443,969,159,000 |
I am trying to write a script(script1.sh) that gives the sum of each digits in the first number, raised to the power of second number. So
./script1.sh 12345 2
should output 55
(because 1+4+9+16+25=55)
or ./script1.sh 3706907995955475988644381 25
should output 3706907995955475988644381.
I wrote a script but in so... |
shell arithmetic in bash uses the widest integer type supported by your C compiler. On most modern systems/C compilers, that's 64 bit integers, so "only" covering the range -9223372036854775808 to 9223372036854775807, and wrap for numbers out of that. In order to do this you will need to use another tool, such as bc:... | Mathematical operations - Bash script |
1,443,969,159,000 |
I'm trying to call this shell script from within the CLI of GRASS GIS:
for (( day=5; day<367; day+5 )); do
# commands that I've tested without a loop.
done
exit 0
returns
Syntax error: Bad for loop variable
|
Perhaps GRASS GIS pre-defines a variable named "day"?
The code doesn't work in straight bash by the way. You don't actually increment the value of "day".
#!/bin/bash
for (( day=5; day<367; day=day+5 )); do
# commands that I've tested without a loop.
echo $day
done
exit 0
That works for me, bash 2.05b on a ... | Why does this incrementing for loop return a bad variable? |
1,443,969,159,000 |
I want to loop through a set of folders, specified within the script and print all files that are empty. I use this script:
array=("folderA" "folderX")
for file in ./"${array[@]}"/*; do
if [ -s "${file}" ]; then
echo "$file"
fi
done
This does not work, I only get the output of the first folder specifi... |
No need to iterate,
array=("folderA" "folderX")
find "${array[@]}" -maxdepth 1 -type f -empty
| Bash - looping through specified folders to find empty files |
1,443,969,159,000 |
In one directory, I have several PNGs and one text file. The PNGs are named after UPC barcodes, like 052100029962.png, 052100045535.png, etc., and I have one text file upcs.txt where each line contains the UPC code merged with product name, like so:
...
052100029962mccormickpepper
052100045535mccormickonesheet
...
I ... |
You have to use a delimiter for a file containing two fields per row. Here a sed inserts this delimiter and the result is given line by line to mv
#!/bin/bash
while read -r oldname newname; do
[ -f "${oldname}.png" ] && echo mv -- "${oldname}.png" "${newname}.png"
done < <(sed 's/^[0-9]*/& /' upcs.txt)
Remove ech... | change filename based on current filename matched with separate file content |
1,443,969,159,000 |
Given the python script
if __name__ == '__main__':
print("first")
print("second")
print("third")
the bash script
#!/usr/bin/env bash
declare -a choice=$( python3 test.py )
echo "You chose "
for c in "${choice[@]}"; do
echo "> ${c}"
done
should print
You chose
> first
> second
> third
but instead, i... |
The Python script prints three lines with text. To read these into an array in bash, use readarray:
readarray -t chose < <( python3 test.py )
printf '> %s\n' "${chose[@]}"
The readarray -t command will read lines into the given array from standard input. Standard input is redirected from your Python script using a ... | Issue with `echo` in bash when looping over output of python script |
1,443,969,159,000 |
Both of the following lines do return the list of dirs of one of my directories.
The first of them use a name pattern whereas I need to choose dirs given they really are directories to then process them in a loop. I thus would like to use the second:
ls -l | awk '{print $9}' | grep 'dirsPrefix*'
find . -maxdepth 1 -... |
You're trying way too hard to get the directories in the current directory. All you need to do is:
for dir in */; do echo "dir: $dir"; done
# .........^^
If you want to store them in an array:
dirs=( */ )
| ksh loop: "for dir in find .. do" not working, unlike "for dir in ls .. do" |
1,443,969,159,000 |
I am trying to process some files in directory using foreach loop for ls output:
IFS=$'\n'
for i in $(ls -1Atu); do
echo "$i"
done
At first time i thought it works, but when i created file with name like * or filename*, shell add additional iterations, because * interpreted as wild char.
But if I escape ls outp... |
Background reading: Why does my shell script choke on whitespace or other special characters?, Why you shouldn't parse the output of ls
Setting IFS to a newline means that only newlines, and not spaces and tabs, will be treated as separators during the expansion of the command substitution. Your method will not suppor... | Foreach loop for ls output |
1,443,969,159,000 |
Under a directory called a there are many subfolders where I want to do something. The same for all. I do the following but it applies only to the first subdirectory:
for i in "a/*"
do
#echo $i
cd $i
mkdir test
mv *_no test
touch aaa
cd ..
... |
When using globs, you should remove the quotes. If not, the globs is not expanded.
So :
for i in a/*
| Why the code in a for loop is executed only in the first directory in a bash shell? |
1,443,969,159,000 |
I seem to have a little bit of an issue with spaces when trying to use for loops and grep together. The whitespace is important because, for example, I'd like to match 'k117_19650 ', but not 'k117_196509 '. Help would be appreciated!
for i in 'k117_19650 ' 'k117_460555 ';do
grep -A1 $i final.contigs.fa >> gene.fa
... |
The problem you are facing is related to your use of shell variables. In particular when using variables which contain "non-standard" characters such as whitespace, always quote your variables when using them, see e.g. discussions here:
Security implications of forgetting to quote a variable in bash/POSIX shells
Why ... | For loop with grep and spaces |
1,443,969,159,000 |
for (( a=1;a<=$(wc -l sedtest1);a++ ));do echo $a; done
Gives me an error:
-bash: ((: a<=21 sedtest1: syntax error in expression (error token is "sedtest1")
|
The output of wc -l sedtest1 will be something like:
21 sedtest1
So the test will become something like a <= 21 sedtest1 which is invalid.
Also, that does mean that the wc command will be run for each iteration of the loop. If the content of the sedtest1 file doesn't change between each iteration, it would be better ... | Command substitution not working inside for loop condition |
1,443,969,159,000 |
I want to write a file using echo command. The echo commend will get data from anther file.
Here is the echo command:
echo '{
name: $name
id: $seq
}
I have a txt file:
customer 1
customer 2
customer 3
So I want to generate a file doing echo and replace $name from fist line from the txt file.
And... |
try
awk '{printf "{\n\tname: %s\n\tid: %d\n\t}\n",$0,NR}' file.txt
where
printf will skip line, add tab and format string.
for id: argument, you can either use second field in your sample file, or generate one from line number (that is NR (Number of Record) value).
| While read from file with sequence number |
1,443,969,159,000 |
Firstly , In the /tmp/test file path I have the below directories
amb
bmb
cmb
By running the find command, I am getting the below list of files inside these three directories:
amb/eng/canon.amb
bmb/eng/case.bmb
cmb/eng/hint.cmb
I am trying to take each file from this list1 using a for loop and based on the file type... |
I think you're trying to apply a different action depending on the file suffix:
#!/bin/bash
while IFS= read -d '' -r file
do
# amb/eng/canon.amb
extn=${file##*.}
case "$extn" in
(amb) finallist+=("${file//amb/amx}") ;;
(bmb) finallist+=("${file//bmb/bmx}") ;;
(cmb) finallist+=("${file//c... | For loop with Multiple IF condition's in Shell scripting |
1,443,969,159,000 |
I want to make a bash script (split.sh) that iterates across multiple dirs with same suffix, and then runs a function for specific files within them. I am almost there:
#!/bin/bash
path="/mypath/MAP-9-[0-9][0-9][0-9]"
for filename in $path/*bam; do
[ -e "$filename" ] || continue
echo $filename
for chr... |
/mypath/MAP-9-[0-9][0-9][0-9]/*.bam is a shell glob, or filename expansion expression. It expands to a list of matching files - you can use that to iterate over your input files, but you can't expect it to work as a "per iteration" wildcard to generate the corresponding output files. I think what you probably want ins... | Unix. Run script across multiple dirs on specific files, where pathname has regex |
1,443,969,159,000 |
This feels so simple, and yet I'm entirely stumped. Needless to say I am absolutely new to this. I have a directory with files numerically numbered from 000 to 020. I would like to rename these files by adding 1 so that 000 becomes 001 etc. Ideally with an awk command but any suggestion would be greatly appreciated, t... |
With zsh instead of bash, you could do:
autoload -Uz
zmv -f -n '*(#qnOn)' '${f//(#m)<->/${(l[3][0])$((MATCH+1))}}'
To increase every number in names of the files in the current directory and left-pad them with 0s to a length of 3. So for example foo-1-2-003.ext is renamed foo-002-003-004.ext or 012 to 013.
(If the wh... | How to rename numerically titled file names by 1 digit? |
1,443,969,159,000 |
when I change any configuration I made a copy of the original file with suffix .original. Now I am composing a simple script that will find all *.original files and work with both versions, ie with and without .original suffix.
I do use command locate with regular expression to avoid mismatched files with the original... |
Backticks require more escaping. This is one of the reasons you should prefer $() (see e.g. "backslash fun" in this answer: What's the difference between $(stuff) and `stuff`?).
Due to not enough escaping inside the backticks, the dot you wanted to escape is unescaped when the string is ultimately interpreted as regex... | For loop and locate command with regular expression mismatched |
1,443,969,159,000 |
root@kali-linux:~/Softwares/Softwares/Tools/dirsearch# array=()
root@kali-linux:~/Softwares/Softwares/Tools/dirsearch# for i in 1 2 3 4
> do
> array+=($i)
> done
root@kali-linux:~/Softwares/Softwares/Tools/dirsearch# echo $array
1
root@kali-linux:~/Softwares/Softwares/Tools/dirsearch# for i in 1 2 3 4; do array+=( $i ... |
Your loop is fine (except that you forgot to quote $i), the problem is in your echo $array, which doesn't print all the elements of the array in bash.
bash has copied the awkward array design of ksh instead of that of zsh, csh, tcsh, rc...
In ksh, $array is short for ${array[0]} (expands to the contents of the element... | Bash array arent adding elements to last |
1,443,969,159,000 |
I wrote the following for loop (spread over multiple lines here for better readability):
for F in CLEAN_READS/*_1.fa; do
R=${F%_*}_2.fa; BASE=${F##*/};
SAMPLE=${BASE%_*};
metascript assembly -1 $F -2 $R -o folder_${BASE%_*} &
done
When I run the loop all scripts are started in parallel. How can I change the loo... |
The reason for this behaviour is that you included a & at the end of your command, which sends the command to the background and immediately passes on to the next.
The loop should behave as you intended when you remove that &. Note that instead you must put a ; to end this instruction (when placing it all on one line,... | How to convert my For loop into sequential execution |
1,443,969,159,000 |
I have a bash script:
for j in "$(ls -d */)"; do
echo "$j"
echo "$j"
done
and this outputs:
dir1/
dir2/
dir3/
dir1/
dir2/
dir3/
What I want it to output is this:
dir1/
dir1/
dir2/
dir2/
dir3/
dir3/
How do I get it to output this way?
(This is a toy example, what I really want it to do is cd into the direct... |
Parsing the output of ls as you're doing is not a good way to do this.
But with that said, your problem is the quoting:
rm -rf dir?
for j in 1 2 3; do mkdir dir$j; done
for j in $(ls -d */); do
echo "$j"
echo "$j"
done
dir1//
dir1//
dir2//
dir2//
dir3//
dir3//
With quotes as your post has, the entire output ... | Bash for loop executes multiple echo statements "out of order" |
1,443,969,159,000 |
I am trying to manipulate the same text file across multiple hosts. The command I currently have it:
for host in $(cat /etc/hosts | grep text | cut -d' ' -f 1 | sort -u); do
ssh $host \
sudo sed -i "s/enabled = 1/enabled = 0/" /etc/yum.repos.d/testing.repo
done
The sed command itself works locally on the host... |
Try this,
for host in $(grep test /etc/hosts | cut -d' ' -f 1 | sort -u); do
ssh $host 'sudo sed -i "s/enabled = 1/enabled = 0/" /etc/yum.repos.d/testing.repo'
done
we should wrap around the remote commands with quotes.
| Using sed command in for loop across multiple servers |
1,443,969,159,000 |
I wrote a script that will find objects that contain spaces in the name, and replaces each space with an underscore. The object type is based on a single object selection.
How can I process all object-types as an alternative option? I was thinking maybe an if-then-else along with and inner for loop?
#!/bin/sh
printf ... |
When you want to present a menu to your user, think of the select command:
# Ask the user which object type they would like to rename
objects=( policy netgroup zonegroup host iprange ipaddr subnet netmap )
PS3="Which network object type would you like to edit? "
select object in "${objects[@]}" all; do
[[ -n "$o... | Process one or multiple objects from a list [closed] |
1,443,969,159,000 |
I was searching for List of Open Files based on Ips amd Processes. I used below command
for i in `sudo netstat -tulpna|awk '{print $5}'|grep -E "[0-9]{3}"|grep -v "^192\|10"|cut -f1 -d ":"`;do sudo netstat -tulpna|awk '/XXX.XXX.XXX.XXX/ {print $7}';done
26181/java
26181/java
26181/java
26181/java
26181/java
2... |
Your awk script:
awk "/$i/ {print $7}"
Here, $7 is expanded by the shell and is most likely empty, resulting in the command
awk '/something/ {print }'
Instead, you may escape the $ in $7 from the shell:
awk "/$i/ {print \$7}"
This is ok in a short awk script like this. In a more complicated script, one should proba... | AWK different result |
1,443,969,159,000 |
Is there a way I could eliminate the last four characters with regex in the below one line script as I convert .wav files into .mp3 files. As of right now my single line script produces files ending in .wav.mp3
for i in *.wav; do avconv -i "$i" "$i".mp3;done
Produces the below output
Sanctify, Separate, & Succes... |
You don't want a regex, you want to use Bash's parameter expansion to remove the file extension in transit:
for i in *.wav; do avconv -i "$i" "${i%.*}".mp3; done
Here, "${i%.*}" is expanded as the pattern at the end of the parameter, as defined by everything (*) after the . deleting the shortest match, ie., .wav.
You... | regex to remove last four characters |
1,443,969,159,000 |
I have two variables
VAR1="1 2 3"
VAR2="Bob Tom Kate"
I want to echo something like this but I don't know how to use multiple variables in a loop:
1 for Bob
2 for Tom
3 for Kate
All I can is:
(
for i in $VAR1; do
echo "$i"
done
)
|
In zsh:
var1=(1 2 3)
var2=(Bob Tom Kate)
for i j in ${var1:^var2}; do
printf '%q, %q\n' $i $j
done
If those variables may contain empty values:
var1=('' 2 3)
var2=('Bob XIV' Tom '')
for i j in "${(@)var1:^var2}"; do
printf '%q, %q\n' "$i" "$j"
done
(or "${var1[@]:^var2}", the point being to get a similar behavio... | "for i in" loop with multiple vars |
1,443,969,159,000 |
I want to determine all broken symlinks within a directory.
In ignorance of a better solution, I tried this simple bash one-liner (bash version is 4.2.46, which may be worth mentioning because it's a bit dated):
for f in $(ls); do test -L "$f" || continue; test -e "$f" || echo "$f deadlink"; done
Unfortunately this d... |
I suspect the problem comes from ls’s use of colours in its output. Since you’re parsing ls’s output, if ls outputs colours, the corresponding escape codes will end up in the values given to f, and test will fail to find a matching file. Since test fails the test without any output in such cases, you wouldn’t be any t... | Why does the test command apparently choke on a for loop variable? |
1,443,969,159,000 |
Hello I am learning Scripting here. I am trying to write a simple script using the 'for' loop.
I have hundreds of folders in a folder called user.
if i run this command i get a list of folders that i need to move to another folder
cat failed | awk -F ":" '/FAILED/ {print $1}' | uniq
i.e folders under users that have... |
With GNU xargs and a shell with support for ksh-style process substitution, you can do:
xargs -rd '\n' -I USER -a <(awk -F : '/FAILED/ {print $1}' failed | sort -u
) cp -r users/USER user/failed/USER
With zsh, you could do:
faileduser=( ${(f)"$(awk -F : '/FAILED/ {print $1}' failed | sort -u)"} )
autoload zargs
zar... | Looping through variables which is an output of another command |
1,443,969,159,000 |
I am not even sure if this is possible or not. I am trying to create a loop where i can curl with different values from a file.
for i in `cat id`;
do curl -X POST 'https:/myurl \
--header 'X-XX-Authorization: XX' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'ACS-Licensing-Ack: XXXX' \
--head... |
You cannot use single quotes ' for variables as anything between them will be treated as literal text and not be expanded by the shell.
Instead use double quotes ".
Also find is an utility to search files, not in files.
The following should work:
#!/bin/bash
for line in $(cat ./id)
do
curl -X POST 'https:/myu... | Trying to loop values into curl command from a file |
1,443,969,159,000 |
I want to create a new column in my file that sums the values of the 2nd and 3rd column for each line.
For example I want
1 2 3
4 5 6
7 8 9
to give me
1 2 3 5
4 5 6 11
7 8 9 17
I've seen other posts doing it with awk but I want to know if there is a way of doing it with loops so that it will read each line and perf... |
You could do
$ while read a b c; do
printf '%d %d %d %d\n' "$a" "$b" "$c" "$((b+c))"
done < test1.txt
1 2 3 5
4 5 6 11
7 8 9 17
but don't - see Why is using a shell loop to process text considered bad practice?
If your shell's read builtin provides array-reading functionality, you could do something like this ... | How to create a column that sums other columns using loops? |
1,443,969,159,000 |
backup/ has the following files.
ubuntu@ip-172-31-8-46:~/$ ls backup/
itrpl_dsm_10_1.tif itrpl_dsm_12_3.tif itrpl_dsm_2_3.tif itrpl_dsm_4_3.tif itrpl_dsm_6_3.tif itrpl_dsm_8_3.tif
itrpl_dsm_10_2.tif itrpl_dsm_12_4.tif itrpl_dsm_2_4.tif itrpl_dsm_4_4.tif itrpl_dsm_6_4.tif itrpl_dsm_8_4.tif
itrpl_dsm_10_3.tif ... |
You should use ${i} not $i. i.e.
for (( i=1; i<=12; i++ )); do tar -czvf itrpl_dsm_$i.tar.gz itrpl_dsm_${i}_*.tif; done
Because bash will look for variable name i_, but there is no variable with this name, so it will replaced with nothing.
So the pattern will become itrpl_dsm_*.tif and then *, wildcard will expand an... | tar command in for loop starts from the wrong number |
1,443,969,159,000 |
I am trying to create a script that goes through a document and finds the highest character length in a column and return it. This script returns 78,78,78,78 when, what im aiming for is 10,11,14,51
for ((i=1;i<=4;i++)); do
awk -F"|" '{ print length($i) }' contact_d.csv | sort -nr | sed '1!d';
done
contact_d.csv con... |
The following code should work:
awk -F'|' '{for (i=1;i<=NF;i++) {len=length($i); if (len>lval[i]) {lval[i]=len; lpos[i]=FNR;}}} END{for (i in lval) printf("Longest value of column %d: %d (line %d)\n",i,lval[i],lpos[i])}' contact_d.csv
For the above example, it returns
Longest value of column 1: 7 (line 1)
Longest val... | finding the highest character length in each column using a loop and awk |
1,443,969,159,000 |
I have a file 'book'(not txt) which contains text. I also have a list of words which I need to delete from said file.
I have written this script but for some reason when I try to check and see if the file was changed after execution I get no changes. I tried outputing the result into book > output.txt but still 'outp... |
Variables are not expanded inside single quotes, but are expanded inside double quotes. You should go for
for word in am pm cm words count etc
do
sed -i "s/${word}//g" book
done
Notice you could also call sed only one time and achieve the same with
sed -i "s/am\|pm\|cm\|words\|count//g" book
| using sed in a for in loop to remove words from file |
1,443,969,159,000 |
I would like to understand the for-loop below and perhaps simplify it.
For example, I'd like to concatenate the rem files for each sample in the directory.
Files:
file1.1.fq
file1.rem.1.fq
file1.2.fq
file1.rem.2.fq
file2.1.fq
file2.rem.1.fq
file2.2.fq
file2.rem.2.fq
for-loop:
list=`for i in *rem*.1.fq; do echo $i |... |
Try:
for i in *.rem.1.fq; do
cat -- "$i" "${i%.1.fq}.2.fq" > "${i%.1.fq}.b.fq"
done
Maybe add a check for the existence of files:
for i in *.rem.1.fq; do
if [ -e "${i%.1.fq}.2.fq" ] && [ ! -e "${i%.1.fq}.b.fq" ]; then
cat -- "$i" "${i%.1.fq}.2.fq" > "${i%.1.fq}.b.fq"
fi
done
The method presented... | for-loop simplification |
1,443,969,159,000 |
I want to store a list with name and email address and use it in the single for loop. And I want to do it in Shell.
Knowing that shell list has a white space separator
list = "john, [email protected]" "doe, [email protected]" "jenny, [email protected]"
for i,j in $list; do
echo "Dear $i, email text" | mail -s "He... |
If your shell supports them, you could use an associative array for the first case:
declare -A list=([john]="[email protected]" [doe]="[email protected]" [jenny]="[email protected]")
for i in "${!list[@]}"; do
echo "Dear $i, email text" | mail -s "Hello $i" "${list[$i]}"
done
For the second case, a while loop:
wh... | List with two values in every List Item |
1,443,969,159,000 |
commrads!
I have a file:
# cat file
'\\.\Aktiv Co. Rutoken S 00 00\USER1@R69-20180109'
'\\.\Aktiv Co. Rutoken S 00 01\USER2@R69-20180109'
and i need execute line by line:
for LINE in `cat file`
do
/opt/cprocsp/bin/amd64/certmgr -inst -cont $LINE
done
BUT! The file has special content like: ' \. . and etc.
And whe... |
Yes, when you iterate over the output of cat file, you iterate over the words.
One solution:
PATH=/opt/cprocsp/bin/amd64:$PATH
while IFS= read -r line; do
certmgr -inst -cont "$line"
done <file
This will read the lines, one by one, and properly read the backslashes and the spaces between the words. Notice the q... | Special content and line by line [duplicate] |
1,443,969,159,000 |
In Ubuntu 16.04 with Bash I had a problem when I didn't have a convenient way to upgrade all my WordPress components (core, translations, theme, plugin) and I used the following code to solve it:
cat <<-EOF > /etc/cron.daily/cron_daily
#!/bin/bash
drt="/var/www/html"
for dir in "$drt/*/"; do
if pus... |
How does the dir variable resembles the asterisk (*) coming a little bit after it in the same line (how is the Bash interpreter knows that $dir [iteratively] represents each directory inside /var/www/html/?
That's just how Bash shell globs work/behave, but you are mistaken about one thing: dir/* is a glob which incl... | How does pushd work? |
1,443,969,159,000 |
As I was trying to fix the episode numbers of a TV series I toyed with the rename function and trying to pass the return from printf as the rename parameters, but could not do it. I tried just about every combination of
for j in $(seq 1 9);
do
rename 's/"$( - "`printf "%d" ${j}`" - )"/"$( - "`printf "0%d" ${j}`" ... |
You are single quoting the entire expression, so no shell interpolation will happen, and Perl will see the most curious regular expression of "$( - "printf "%d" ${j}" - )" which is interpolated by Perl into something like
% perl -E 'say qq{"$( - "`printf "%d" ${j}`" - )"}'
"42 640 - "`printf "%d" `" - )"
%
because y... | How to use rename command with printf |
1,443,969,159,000 |
I have about 10k (approx 180x50x2) CSV files which I want to join together as following, but the inner for loop fails because of some syntax error; I cannot see the error in lastFile
#!/bin/bash
dir='/home/masi/CSV/'
targetDir='/tmp/'
ids=(118 119 120)
channels=(1 2)
for id in ids;
do
for channel in ... |
There is a missing do in your second for loop:
for id in ids;
do
for channel in channels; do # <----- here ----
# example filename P209C1T720-T730.csv
lastFile="$dir'P'$id'C'$channel'T1790-T1800.csv'"
# show warning if last file does not exist
... | Why "syntax error near unexpected token"? [closed] |
1,670,167,193,000 |
I'd like to use variables inside the for loop in shell.
My current code:
VAA="1st_first"
VAB="2nd_second"
VAC="3rd_third"
for i in VAA VAB VAC; do
if [[ "${i}" =~ ^[A-Za-z]*$ ]]; then
echo "$i variable is a word"
else
echo "$i variable is not a word"
fi
done
The expe... |
I usually solve thing like this with associative arrays. But I do not know if this is an efficient solution. But this does not guarantee the original order as it looks in the output
#!/bin/bash
declare -A varCheck
varCheck=( [VAA]="stfirst" [VAB]="2nd_second" [VAC]="3rd_third" )
for var in ${!varCheck[@]}; do
... | Using variables inside the for loop in shell [duplicate] |
1,670,167,193,000 |
I know that the following is bad:
for i in `ls -1 *.MOV` ;do ...
and that the proper syntax is
for i in *.MOV ;do ...
But what are the mechanics behind it? I mean, what part of *.MOV tells the for command that I'm talking about filenames? Is there an assumption made in the for code that says "given no other p... |
Yes :-) The shell is expanding the wildcard to the set of files matching the wild-card expression, in your example the MOV files in the current directory. But six other kinds of expansion must be considered before this happens.
'Expansion' is described in a detailed way in the manual man bash.
EXPANSION
Expansion is ... | for loop parsing of ls and the magic behind * |
1,670,167,193,000 |
I have 3 files like below:
CV_REF_DATA_09012021.txt
DB_ONLINE_CL_09012021.txt
DFR_CL_INS_09012021.txt
I want to check if the files are present in /NAS/CFG/ and then add it to an array.
It's not required that all the 3 files are present at all times. So, it can either be 1, 2 or all the 3 files. If there are no files ... |
Your description of what you want to happen, depending on the existence of the files, is a bit vague. It's also unclear if you wish to collect the names separately for each filename prefix or together. It may also be better to pick a particular date, for example, and try to find the set of files from that. The code ... | Add values to an array and loop based on that |
1,670,167,193,000 |
I'm writing a BASH script that asks a user for the number of columns and the number of items to put in the columns. The script will then put the numbers in the columns using for loops.
# Number of columns
cols=$1
# Number of items
num=$2
# Iterator variable
count=1
# Number of rows
rows=$(( ($num + ($cols - 1)) / $... |
You never have to calculate the number of rows needed. You just need to make sure that you insert newlines after every $cols number.
Using seq and awk:
$ num=28
$ cols=6
$ seq "$num" | awk -v cols="$cols" '{ printf "%-4d", $1 } NR % cols == 0 { printf "\n" } END { printf "\n" }'
1 2 3 4 5 6
7 8 9 10 ... | Displaying number of columns and items in columns using a for loop |
1,670,167,193,000 |
I'm not quite sure what I'm doing here but I need to be able to get an unlimited number of integers to be provided as arguments
so far I have
for sum in $@; do
sum=$(($1 + $2 + $3))
done
echo $sum
output is
5
and my understanding is that it's taking the positional parameters here but How would I get it to do... |
When you do for sum in $@ what's happening is that the variable $sum is being set to each value in turn.
You can see this with a simple test
for lp in $@
do
echo $lp
done
If you run this with "10 20 30 40" as parameters then you'll see it output each value in turn.
So what you need is a loop with a temporary variab... | setting number of integers for unlimited argumments |
1,670,167,193,000 |
I am trying to take a file, modify this file by using a value from a for loop (using sed) and redirecting it to a directory that has been created during the same for loop.
Original file > Make directory > process file (make changes) > redirect output to directory
My problem is at making the directory with the values o... |
There appears to be many little things in that code snippet that may be causing confusion.
First off, as written, $k can sometimes start with a dot (e.g. .1, .2, etc.), which in Unix defines the directory to be a hidden directory. The first thing I would check is whether those directories are created as hidden:
ls -A
... | Creating directories inside a directory, from variable values, to redirect output from sed |
1,670,167,193,000 |
I have a script I came up that simply executes another process into the background that attempts to control the max number of processes running (300 in this case).
It initially executes scripts at approx. 1-2 milliseconds, but after several hours of running it will eventually slow down in a linear slope to 200ms - 3... |
The original code.
When you start off you just start 300 copies of cli.php. This takes about 1200 processes because you want to measure the time taken to launch.
You then loop the variable crd from 300 to 9999999.
If the shell thinks there are spare slots in the threads array it will start a new cli.php using the 4 ... | Bash script that runs parallel threads slows down substantially over several hours |
1,670,167,193,000 |
Suppose I have this code:
for i in $(find * -type f -name "*.txt"); do
# echo [element by it's index]
done
How do I access, if possible, an element by it's index?
|
Your command
$(find * -type f -name "*.txt")
will return a (space-separated) bash list, not an array, hence you cannot really access the individual elements in a "targeted" way.
To convert it to a bash array, use
filearray=( $(find * -type f -name "*.txt") )
(note the spaces!)
Then, you can access the individual ent... | Reference items in bash for loop from find command |
1,670,167,193,000 |
I have a numbered list of files like this:
01_file_name.log
01_file_name.txt
02_file_name.log
02_file_name.txt
03_file_name.log
03_file_name.txt
04_file_name.log
04_file_name.txt
05_file_name.log
05_file_name.txt
I want to insert new files for all 03* and 04* files. So from number 03 on wards all files need to be mo... |
This does what you want. One thing: It only works in BASH, I think.
MAXDIGITS is optional, I put it there in case you need to work with triple digits or more. If you don't use it, delete the corresponding lines.
#!/bin/bash
BOTTOM=$1
SHIFT=$2
MAXDIGITS=0$3
for filename in $(ls -r *.{txt,log}); do
... | Bash - move/rename numeric sorted files from input number onwards [duplicate] |
1,670,167,193,000 |
1. Summary
I want to print variables from loop.
If I place echo $i after command from loop:
Travis CI build passed.
elif I place echo $i before command from loop:
I get exit code 1.
I don't find:
why is this happening,
how I can print variable before command.
2. What the script should do
I use HTMLTidy for ... |
The exit status of a for loop compound command is that of the last command executed in it¹.
for cmd in true false; do
"$cmd"
done
Returns false (a non-zero exit status) because false was the last command run.
echo will return true as long as it successfully manages to write what we're telling it to.
If you want to ... | Print variable inside loop |
1,670,167,193,000 |
Below is the script i drafted, that will work based on the SIDs it will get from
ps -ef | grep pmon
Once the SID is grepped, it will pass the SID to dbenv() to set the necessary parameters, and it also cuts the DB_VERSION from /etc/oratab entries.
Based on the version, if 12 or 11 then the script should execute a b... |
This question probably belongs on
https://codereview.stackexchange.com/ instead of here, but here are my recommendations:
use $() rather than backticks for command substitution.
you (almost) never need to pipe grep in to awk. For example, instead of:
ps -eaf | grep pmon | grep -v grep | awk '{print $8}'
you can do... | Execute a block based on the output of a variable [closed] |
1,670,167,193,000 |
I need a script in order to, giving a packages list as arguments, the script performs the installation of the packages in one row. For example launching the script in this way:
script package1 package2 package3
it performs the installation in this way:
yum -y install package1 package2 package3
Clearly I'm in a situa... |
This seems like a reasonable thing to do in your script:
yum -y install "$@"
"$@" will expand to the individually quoted command line arguments of the script itself, just like it would do in your for-loop. But instead of looping over the arguments, you pass them all to yum -y install in one go.
| how to iterate installation in a row |
1,670,167,193,000 |
Say I create a file ~/myScript.sh:
#!/bin/sh
for myVar; do
echo "Hi"
done
If I execute bash myScript with no arguments I'll get nothing but if I'll execute it with one or more arguments I'll get the output per the number of these variables (the variable seems to make the script dependent in passed arguments):
ba... |
myVar is not undefined if the script is called with positional parameters. From man bash:
for name [ [ in [ word ... ] ] ; ] do list ; done
[...] If the in word is omitted, the for command executes list once for each positional parameter that is set
But you do not use $myVar.
for myVar; do
echo "$myVar"
done
| Bash: One argument per one undefined variable |
1,670,167,193,000 |
A for loop that steps through a list of quoted headers:
for h in "header" "header 2"; do
echo $h
done
returns
header
header 2
I'd like to reference the headers somewhere else to clean it up, like assigning them to a variable.
headers='"header" "header 2"'
for h in $headers; do
echo $h
done
but this returns
... |
Another way of doing this is by changing the fiels seperator variable like:
headers="header,header 2"
IFS=,
for h in $headers; do
echo $h
done
Note: If you have other loops which requires the default IFS value you can first save the IFS value into a temporary variable.
See also man bash and search for IFS for... | For loop with quoted entries |
1,670,167,193,000 |
I am running the following code
for d in ./*/ ; do (cd "$d" && dcm2nii -n y -r y -x y -g n ../*/dicom/); done;
in order to execute the dcm2nii program on all subfolders of ./*/ (they are all titled "dicom") and to save the output to those same subfolders. The loop works but it runs twice creating duplicate output fil... |
I guess you had 2 subfolders while testing/executing your command.
Your code:
for d in ./*/ ; do (cd "$d" && dcm2nii -n y -r y -x y -g n ../*/dicom/); done;
first enters a subfolder $d
then does dcm2nii ... on ../*/dicom, which translates into: subfolder "dicom" of all folders of the superfolder
then goes to the sec... | For loop works but loops twice |
1,670,167,193,000 |
If I ls files without a for loop in a remote host everything is fine however, if I capture the ls in a variable and try to echo each file it fails as the variables don't expand/have a value.
What I mean:
IFS=$'\n'
servers=(
blue
green
red
)
for i in ${servers[@]}; do
ssh $i "
ls /dir/xyz_${i}*/details.... |
The issue is that the command substitution that you want to run on the remote servers is run locally. This is due to the substitution occurring within double quotes, meaning the local shell will compute its expansion before calling ssh.
Also, reading the output of ls is ill-advised (see Why *not* parse `ls` (and what... | How to run for loop over SSH on remote so that variables expand? |
1,670,167,193,000 |
I have a python program that requires 2 arguments input-file and output-file.
It reads input-file and creates a copy of that file with some modifications in the output-file.
I created a text file with a set of arguments. It has multiple sets of arguments on multiple lines. But for 1 execution of a program it needs to... |
Running a command for each line of some file with the whitespace-separated words in those lines passed as arguments to the command is what xargs -L1 does:
So, it would be just:
xargs -L1 <File-With-Multiple-Arguments-Per-Line.txt python MyProgram.py
As xargs understands some form of quoting, it can be used for arbitr... | Pass multiple arguments from single line from a text file to teminal |
1,670,167,193,000 |
I am trying to loop through directories within a given folder and I want to skip a particular directory name. I have written this bash script to do it, but this is giving me errors. Please tell me where I am going wrong:
for f in *
do
if [ -d "$f" ]; then
if [ -d "TEST"];then
echo "skip TEST direct... |
Your if statement is incorrect. Try changing your 2nd if statement to the following.
for f in *
do
if [ -d "$f" ]; then # Modify to [[ ! -L "$f" && -d "$f" ]] to check only for directories and not symlinks since -d will also get symlinks
if [ "$f" = "TEST" ]; then
echo "Skipping $f dir"
... | looping through directories in bash skipping a particular directory name |
1,670,167,193,000 |
I have a podman-compose file:
version: "3.8"
services:
kiwix-serve:
image: docker.io/kiwix/kiwix-serve:3.3.0-1
volumes:
- kiwix_data:/data
- /home/meijin3/zim/gutenberg_en_all_2022-10.zim:/data/gutenberg_en_all_2022-10.zim
- /home/meijin3/zim/wikipedia_en_all_mini_2022-09.zim:/data/wikipedi... |
I resolved my issue by assigning the output of my find command to an array, i.e.,
zim_files=($(find /home/meijin3/zim/*.zim -printf '%f\n'))
I modified my for loop to iterate over this array:
for i in ${zim_files[@]}; do
sed -i -e '\,kiwix_data,a \ \ \ \ \ \ - /home/meijin3/zim/'"$i"':/data/'"$i" "$yaml"
sed -i ... | Errors appending text with `sed` |
1,670,167,193,000 |
I'm trying to loop over files with having different searching conditions based on the folder which I used with a case statement.
basically it's:
#!/bin/bash
case folder in
"Testordner")
search_filename=*_0_*.txt
;;
"Ordner2")
search_filename=*_65_*fg*.txt
;;
*)
;;
esac
for files in $sea... |
In Bash, and with nullglob disabled (generally the default), a glob pattern will evaluate/expand to itself in the case of no matches (e.g., *.txt evaluates to the literal string *.txt). With nullglob enabled (often preferable for scripts), a glob pattern evaluates/expands to an empty string in the case of no matches.... | bash: different behaviour of script and in terminal (loop over files) |
1,670,167,193,000 |
target=${1:-http://web1.com}
while true
do
for i in $(seq 10)
do
curl $target > /dev/null &
done
wait
done
I am just a beginner at writing in programming especially bash.
I want to train my HTTP load balancing by giving 10 HTTP requests at one time. and stop sending the request when it reaches 150... |
If what you want to achieve is to call curl a total of 15000 times, then what you need to do is to run your outer loop 1500 times.
You could do that by simply running the outer loop 1500 times in a similar way that you run the inner loop ten times:
target=${1:-http://web1.com}
j=0
while [ "$j" -lt 1500 ]; do
for... | how to stop while looping for bash |
1,670,167,193,000 |
I have a few folders like [email protected], [email protected], [email protected]. i want to rename them so that it will be name1, name2, name3 etc. i figured out that if they are vise versa i.e name1, name2, name3 i can move it to [email protected] by running
find . -type d -name "*" -depth 1 | while read d; do mv "... |
With a shell such as Bash:
for d in ./*@*/; do mv "$d" "${d%@*}"; done
for d in ./*@*/ loops over all directories in the current directory whose names contain “@”. ${d%@*} is a parameter expansion, giving the value of the d variable minus the last “@” and whatever follows.
You can make this more restrictive, e.g.
for... | how to remove/rename an extension from a folder |
1,670,167,193,000 |
for items in *
do
if [ -f items ]
then
echo $items
fi
done
Look at my directory As you can see my directory isn't empty but, when I run above code it isn't printing anything..
┌──(istiak㉿kali)-[~/ShellProgramming]
└─$ ./practice.sh
|
Thanks to @muru for his comment.
Here's the answer
for items in *
do
if [ -f "$items" ]
then
printf '%s\n' "$items"
fi
done
| why I am not getting any outputs [closed] |
1,670,167,193,000 |
I have the below folder structure in Linux env:
|-- Fixed_Zip
| |-- ipython_notebooks
| | |-- notebook editor for compute_0anXhGEj.ipynb
| | |-- notebook editor for compute_aucScores.ipynb
| | |-- notebook editor for compute_nG27bM3w.ipynb
| | |-- notebook editor for compute_test_scored_scikit1.ipyn... |
"Filenames with spaces" cries out for find and xargs. Read man find xargs and do something like
find Fixed_Zip -type f -name '*.ipynb' -print0 | \
xargs -0 -r -n 1 jupytext --to py
| How to loop over subdirectories and perform action while ignoring spaces in file names [duplicate] |
1,670,167,193,000 |
I am relatively new to Linux in general and I hope someone can help me.
I would like to merge fastq.gz files from 4 different sequencing lanes. Each file has the following name: GC082_F4.lane1.1901.R1.fastq.gz with GC082_F4 the name of the sample, laneX referring to the lane (1 to 4) and R1 refers to the forward or re... |
Simply identify the unique parts of the file and cat those:
cat GC082_F4.*.R1.fastq.gz > GC082_F4_R1.fastq.gz
cat GC082_F4.*.R2.fastq.gz > GC082_F4_R2.fastq.gz
So, if you have multiple samples, you can do:
for sample in GC082_F4 GC083_F4 GC084_F4 GC085_F4 ... GC0NN_F4; do
cat "$sample".*.R1.fastq.gz > "$sample"_R... | For loop to catenate files with two variables |
1,670,167,193,000 |
Need your help on a command that run on a path1 to rename and move files from path2 to path3
Assume
path1 = /data/run/
path2 = /data/output/
path3 = /data/archive/
path 2 contains few files like 'one.txt', 'two.txt' etc...
I want to run a command in path1 which can rename the files 'one.txt' to 'archive_one.txt' and ... |
what you want to do is
for FILENAME in /data/output/*.txt;
do
mv "$FILENAME" "/data/archive/archive_$(basename "$FILENAME")" ;
done
this can be one lined of course.
where
basename "$FILENAME" extract last part of filename
basename "$FILENAME" .txt would do the ame, striping .txt part.
and when posting here t... | Rename and move files from one directory to another directory |
1,670,167,193,000 |
I have 100+ subfolders (P_XXX), each containing three sets of files (run1, run2 and run3):
/Analysis
/P_076
/run1
/run2
/run3
swu_run1_P_076_vol_001.nii
swu_run1_P_076_vol_002.nii
swu_run2_P_076_vol_001.nii
swu_run2_P_076_vol_002.nii
swu_run3_P_076_vol_001.nii
... |
You could use two loops with bash:
cd /path/to/Analysis
shopt -s nullglob
for i in {1..3}; do
for f in */swu_run${i}_*.nii; do
mv "$f" "${f%/*}/run${i}/"
done
done
The enabled nullglob shell option makes sure that the inner loop is not entered if */swu_run${i}_*.nii doesn't match any files (already moved or ... | Move files into sub-subfolders based on their file name, for multiple subfolders |
1,670,167,193,000 |
I'm trying to:
Attach multiple files into one email.
Have the email sent out using a Gmail account with the current date and time in the subject header.
I'm having trouble with the for a loop since I don't want to create multiple emails I just one to create one email with all the attachments included and have the ... |
Here's a bash script that might help others out that I got to work.
#!/bin/bash
currentdir="$(pwd)" #get current directory
fn_dt_now_start=`date '+%Y_%m_%d__%H_%M_%S'`; #use to generate date time
fn_txt=$(ls $currentdir/*.txt) #place txt files found into a variable
for t in ${fn_txt[@]}; do
... | Attaching multiple files using bash and emailing it out using SWAKS or another program |
1,572,335,195,000 |
Here is a little experiment:
t1=$(date +%s%N)
ta=0
for i in `seq 1 1000`
do
t1a=$(date +%s%N)
echo blabla
t2a=$(date +%s%N)
((ta=ta+(t2a-t1a)))
done
t2=$(date +%s%N)
echo diffb: $((t2-t1))ns
echo diffba: $((t2a-t1a))ns
The results:
diffb: 2767264439ns # this is the overall result
diffba: 1482172ns # t... |
The bug is in the last line.
You calculated the time of one iteration. A 1000 times slower, than 1000 iterations.
| Bash loop 1000x overhead over loop core |
1,572,335,195,000 |
I want to use a set of previous variables created to filter columns of a file called a.ped_snps.temp with awk within bash for loop.
For this, I created bash variables: var_i_1, var_i_2, ... var_i_n_blocks to be the lower bound; and var_f_1, var_f_2, ... var_f_n_blocks to be upper bound.
Note that n_blocks afore mentio... |
It looks like you are expecting $var_i_$i to expand to the value of $var_i_1, $var_i_2 and so on - unfortunately it doesn't. To illustrate, suppose we set
$ var_i_1=23; var_i_2=45; var_i_3=67
then
$ for i in $(seq 1 3); do awk -v v_i="$var_i_$i" 'BEGIN{print v_i}'; done
1
2
3
What's happening here is that the shell ... | How to use bash variables in a awk command within bash for |
1,572,335,195,000 |
I would like to compare the 2nd column of file1- freememory with the 2nd column-usedmemory of file2. If file1(2nd column) that is "freememory" > file2 (2nd column) that is "usedmemory" then print file2(1st column)-"machine" can be relocated to file1(1st column)-"storage", else file2(1st column)-"machine" CANNOT be re... |
I'll assume file1 doesn't have an empty 2nd line.
paste -d, file1 file2 | awk -F, 'NR>1{if ($2 > $4) print $3,"can be relocated to",$1 ; else print $3,"cannot be relocated to",$1}'
Using paste to feed awk a single "file" consisting of the combined columns of the respective lines.
The awk itself is pretty straightfo... | compare column of two files and print data accordingly |
1,572,335,195,000 |
I want to create directories in bash by iterating over values from multiple loops (here for simplicity just 2) while skipping identical values. A demonstrating example looks like this:
for i in 1 2 3; do for j in 1 2 3; do mkdir $i$j; done, done
This gives me folders named 11, 12, 13, 21, 22, 23, 31, 32, 33, but I wan... |
Note: The loops below run from 1 to 9 using brace expansions. Use {1..3} or 1 2 3 to do exactly as in the question.
Compare $i and $j to make sure that they are different before creating the directory:
for i in {1..9}; do
for j in {1..9}; do
[ "$i" -ne "$j" ] && mkdir "$i$j"
done
done
The -ne test te... | Skip identical values in nestled for loops |
1,572,335,195,000 |
I'm learning how to make script "fool-proof". I have some scripts that modify files in the current folder but they also modify the script itself. I know it all boils down to the "for" loop with "find" I can't get right.
for f in $(find . -type f | grep -v $0)
My goal is to include all files it can find from the curre... |
Example of the find . -type f ! -path $0 approach. Note how the script only reports the foo.sh within the "d" directory. Not the foo.sh in the current directory.
$ find . -print
.
./a
./b
./c
./foo.sh
./d
./d/foo.sh
$ cat foo.sh
#!/bin/bash
for f in $(find . -type f ! -path $0); do
echo $f
done
$ ./foo.sh
./a
./b
./... | Excluding Bash File from modifying itself |
1,572,335,195,000 |
I have a file which looks like this:
Sender Bob IP 10.1.1.1
Sender Alex IP 10.1.1.2
Sender Jim IP 10.1.1.3
10 lines like this in same format.
I need to echo Name and IP.
While iterating through my for loop of IPs, because i am ping testing each IP.
So far, I have been able to do this:
THEIP=$(cat /tmp/files/extract.t... |
What you want to achieve exactly is unclear, but something like this might work:
Edit1: improved thanks to Glenn's comment
Edit2: completed the code inside the loop
input="/tmp/files/extract.txt"
while read _ id _ ip; do # iterate over the lines
echo -n "Pinging $id @ ip $ip... "
if ping -w 1 $ip 2>&1 >/dev/null; ... | outputting 2 positions from same file into script and then echo |
1,572,335,195,000 |
I am listing files from a folder and taking an input from the user to select one of the files.
files=$(ls ~/VideoExtract/*.avi)
i=1
for j in $files
do
echo "$i.$j"
file[i]=$j
i=$(( i + 1 ))
done
echo ""
echo ""
read -p "Enter the serial number from the above list : " input
clear
Suppose if I have 3 files, the above c... |
(On a mobile so a somewhat shorter than I'd prefer)
=~ is a Regular Expression match. You don't want this here. Use -lt (less than) or -le (less than or equal) instead.
There are also a number of other problems with your code
don't use ls to list a set of files, just use the set of files directly files=(~/VideoExtrac... | while loop to check for user input not in for loop |
1,572,335,195,000 |
I am now developing a script to copy some files from directory A to multiple directories B following some directives , the script is working fine , but when it comes to files with spaces on them , he just considers them as multiple files , for example:
my_super_cool_file_2007039904_11 (3rd copy).pdf
when the file is ... |
Since you're using -maxdepth 1 and -mindepth 1, you may as well just do a simple loop (in bash):
for name in "$parent"/*; do
if [ -f "$name" ]; then
dir=${name%/*} # dir=$( dirname "$name" )
dir=${dir##*/} # dir=$( basename "$dir" )
printf 'The directory is "%s"\n' "$dir"
fi
done
Loo... | for detects the spaces in the file as multiple lines |
1,572,335,195,000 |
I have a simple for loop one liner I use to check for things across a number of servers that have the same password set. I want to develop this one liner into a script that logs into a cluster of servers via IP address, prompts for a password and performs a command. Such as restarting a service. This is what I use:
... |
for i in {1..253}
do
ip=192.168.1.${i}
echo "Enter password for: $ip"
read pswd
case "$pswd" in
*) password=$pswd;;
esac
sshpass -p "$password" ssh -o StrictHostKeyChecking=no username@$ip 'hostname
echo "Checking if foo.log exists: `ls -lh /var/log/foo.log | wc -l`"
echo "Chec... | Bash For Loop - prompt for IP range and password |
1,572,335,195,000 |
Consider the below scenario
2 vms - 192.168.229.131, 192.168.229.132
Both the vms has it's ip as 192.168.229.151 & 192.168.229.152 in it's /etc/hosts file
Say there are around 50 vms like I said above. But as of now, I am considering only the above 2.
I saved ips of the 2 vms in a file named server
#cat server
192.168... |
You need to single quote your here document limit string, otherwise parameter substitution will be enabled. This should work:
#!/bin/bash
cat server | while read line
do
/usr/bin/sshpass -e ssh -t -q -o StrictHostKeyChecking=no root@$line <<'EOF'
echo successfully logged in $line
MYIP=$(ifconfig | sed -En 's/127... | reading file using for, while - behavior |
1,572,335,195,000 |
Hello I have a file called users. In that file i have a list of users for example
user1
user2
user3
Now i have another file called searches where there is a specific string called owner = user for example
owner = user1
random text
random text
owner = user15
random text
random text
owner = user2
so is it possible t... |
Try awk:
awk 'NR == FNR {SRCH[$1]; next} $NF in SRCH {$NF = $NF "@domain.com"} 1' users searches
owner = [email protected]
random text
random text
owner = user15
random text
random text
owner = [email protected]
It adds the addendum if user found in users file.
| Edit a particular string in a file based on another file |
1,572,335,195,000 |
I am writing this bash shell script:
#!/bin/bash
declare -i N
read N
for i in {1..$N}
do
echo "Number: $i"
done
(I believe declare -i N makes the N an integer)
However on running this, I get the following output:
>vim new.sh
>chmod +x passgen.sh
>./passgen.sh
15
Number: {1..15}
Here I want to take the limit from... |
From man bash:
The order of expansions is: brace expansion; tilde expansion,
parameter and variable expansion, arithmetic expansion, and command
substitution (done in a left-to-right fashion); word splitting; and
pathname expansion.
As you can see brace expansion is first, so apparently it is skipped in your problem... | Why am I getting unexpected output while trying to loop for the number of times entered by the user? [duplicate] |
1,572,335,195,000 |
I have a bash script which is supposed to go through a series of files text file. I have written a for loop to do this job automatically for me but I am not getting any output files when the script runs.
I have attempted various single line commands that I have found online, but with no luck. I am looking to break the... |
Assuming that the files are all comma-separated and the first field ($1) contains the year, all you need is:
awk -F, '{print > FILENAME "-" $1 ".dat"}' *yyyymm.txt
| awk command inside bash shell script loop |
1,572,335,195,000 |
I have this script that extracts 200 random characters from a set:
#!/usr/bin/bash
n=$(stat -c "%s" newfile.txt)
r=$(shuf -i1-"$((n-200+1))" -n1)
< newfile.txt tail -c+"$r" | head -c200
for N in {1..10000}; do bash extraction_200pb.sh; done > output.txt
I know shuf is very powerful but I want to include a sampling ... |
This is an implementation of a solution in awk. The data is 8GB of pseudo-random hex digits (actually a hex conversion of about 12 man pages, duplicated 3300 times). It is about 11 million lines averaging 725 bytes per line.
This is a timed execution.
Paul--) ls -l tdHuge.txt
-rw-r--r-- 1 paul paul 8006529300 Dec 24 2... | How to sample without replacement from a script that randomly extracts 200characters using shuf? |
1,572,335,195,000 |
I have a folder with various file types, but I am interested in the files with .img as extension, with the following pattern:
ppi_noTD_d0_P_76con_0001.img
ppi_noTD_d0_P_104con_0001.img
ppi_noTD_d0_P_150con_0001.img
ppi_noTD_d0_P_201con_0001.img
etc.
The only changing bit of the file names is the P_XXX part.
I have c... |
Your stable.txt file was likely created or edited on a Windows system, where the newline is represented by the carriage rturn + line feed sequence (often referred to using the abbreviation CR LF or the escape sequence \r\n).
For instance, assuming this sample file:
printf '%s\r\n' P_76 P_201 >stable.txt
After the fir... | Move specific files to another folder based on partial pattern in .txt file |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.