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 replace the extension name to another and I hope the process will be something like basename + ".done" so test1.jpg becomes test1.done
test1.jpg
test2.jpeg
test3.txt
test4.dummy
Now, what I want is to somehow, put these extension names .jpg,.jpeg,.txt,.dummy in an array, then use that in for loop something like for file in *{.jpg,.jpeg,.txt,.dummy}; do, but I tried it and it does not work, the shell seems to not allow arrays in for loop?
can somebody help me and give me an example how to solve this? thanks!
UPDATE
so, I learned that using for file in *.{jpg,jpeg,test} will solve my problem, but sometimes it fails, specially when there's no file with an extension declared in the array
Example:
test1.jpg
test2.jpeg
test3.test
test4.dummy
Using a bash like:
for file in *.{jpg,jpeg,test,avi}; do size=$(stat -c '%s' "$file"); echo $file filesize is: $size; done
will end up ugly:
test1.jpg filesize is: 2
test2.jpeg filesize is: 0
test3.test filesize is: 0
stat: cannot stat `*.avi': No such file or directory
*.avi filesize is:
the last 2 lines above is unnecessary, I wish there is something like a break where if for cannot find any avi then stop the do
Is this possible?
|
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 off
$ for file in *.{jpg,jpeg,test,avi}; do
echo "$file size is $(stat -c '%s' "$file")";
done
test1.jpg size is 0
test1.jpeg size is 0
test1.test size is 0
stat: cannot stat ‘*.avi’: No such file or directory
*.avi size is
And if we activate nullglob:
$ shopt -s nullglob
$ shopt nullglob ## just to demonstrate that it is on
nullglob on
$ for file in *.{jpg,jpeg,test,avi}; do
echo "$file size is $(stat -c '%s' "$file")"
done
test1.jpg size is 0
test1.jpeg size is 0
test1.test size is 0
Alternatively, you could just make sure that the file exists (I am also using this example top demonstrate that brace expansion is not needed here):
$ for file in *jpg *jpeg *test *avi; do
[ -e "$file" ] && echo "$file size is $(stat -c '%s' "$file")"
done
test1.jpg size is 0
test1.jpeg size is 0
test1.test size is 0
| 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 with adding the video extension.
How can I do that ?
Thanks in advance.
|
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.
The script applies the function first to various image extensions then various video extensions.
#!/bin/bash
# a function to rename all files with a given extension
# takes two arguments: the extension, plus either "IMG" or "VID"
rename_ext() {
# read the arguments to the function
local ext="$1"
local ftype="$2"
# loop over all files with that extension
while IFS= read -r -d '' filename ; do
# read the (sub)directory name
dirname="$(dirname "$filename")"
# find the modification time
modifytime="$(stat -c '%Y' "$filename")"
# determine the new name
local formatted="$(date +'%Y%m%d_%H%M%S' -d @$modifytime)"
local newname="${ftype}_${formatted}.${ext}"
# rename the file (and report that we are doing it)
echo renaming "$filename" to "$dirname/$newname"
mv -n "$filename" "$dirname/$newname"
done < <(find -iname "*.$ext" -type f -print0)
}
# run the function on various image extensions
for ext in apng avif bmp gif jpeg jpg png tif webp ; do
rename_ext "$ext" "IMG"
done
# run the function on various video extensions
for ext in avchd avif avi flv m2ts m4v mkv mov mp4 mpeg mpg mpv mts ogv qt vob webm wmv ; do
rename_ext "$ext" "VID"
done
You might want to try it once with the mv line commented out to make sure it's doing what you expect.
You might also consider using the exif metadata instead of the file modification time, but that's a little more involved.
| 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 folder.
001.txt and 001(1).txt into 001 folder
Base on above question, but does't work. command from above question:
set -o errexit -o nounset
cd ~/myfolder
for file in *.txt
do
dir="${file%.txt}"
mkdir -- "$dir"
mv -- "$file" "$dir"
done
Have tried:
set -o errexit -o nounset
cd ~/myfolder
for file in *(1).txt
do
dir="${file%.txt}"
mkdir -- "$dir"
mv -- "$file" "$dir"
done
This command will create folder for each file.
Any suggestion to distinguish files like 001.txt and 001(1).txt, so we can select the desired file to create one folder, then run another command to archive the same goal?
|
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 if necessary
mv -f -- "$file" "$dir" # Move the file
done
You can prefix the mkdir and mv with echo to see what would happen before you action it.
| 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 folder
so that folder 1 has "1.txt" in it
folder 2 has "2.txt" in it
etc..
I managed to do that with this script:
for i in $(ls -d */); do touch "$i $(basename $i).txt" ; done
The problem is I want to do the same thing but with folders that has spaces in their names.
For example:
If I have a folder named "Test Me"
It will give an error saying something like this:
Me: no directory with that name
It will see only the word "Me" and treat it as a folder and not "Test Me" as a whole.
How can I do that ?
Update
This is the solution, it is commented below by TAAPSogeking (Thanks again to him)
for dir in *; do [ -d "$dir" ] && touch "$dir/$dir.txt"; done
|
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
filter for
directories (including symlinks to directories).
And then create the requested file in the specified
directory
Also you may be interested in shellcheck which point out common errors/bad practices (like the use of ls in this case)
| 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 a2 times
Welcome a3 times
Welcome a4 times
Welcome a5 times
How cam I print a1 as $a1 in the way to have "10" ?
Otherwise I have to do this:
for i in $a1 $a2 $a3 $a4 $a5
do
echo "Welcome $i times"
done
The problem is that I have more than 100 "a" variables and I can not use the last option above
Are good also new suggestion outside of "loops"
Many thanks
|
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
echo "Welcome ${x} times"
done
| 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 for loop
Description of the script:
Variables, required by GitLab's Repository files API:
branch="master"
repo="my-dotfiles"
private_token="XXY_wwwwwx-qQQQRRSSS"
username="gusbemacbe"
I used a declaration for multiple files:
declare -a context_dirs=(
"home/.config/Code - Insiders/Preferences"
"home/.config/Code - Insiders/languagepacks.json"
"home/.config/Code - Insiders/rapid_render.json"
"home/.config/Code - Insiders/storage.json"
)
I used the condition for loop with jq to convert all files from the declaration context_dirs to encoded URLs:
for urlencode in "${context_dirs[@]}"; do
paths=$(jq -nr --arg v "$urlencode" '$v|@uri')
done
I used the condition for loop to download with curl multiple files taken from paths converted by jq. It is important that I used -0 and -J to output the file name, and -H for "PRIVATE-TOKEN: $private_token":
for file in "${paths[@]}"; do
curl -sLOJH "PRIVATE-TOKEN: $private_token" "https://gitlab.com/api/v4/projects/$username%2F$repo/repository/files/$file/raw?ref=$branch"
done
Complete source code:
branch="master"
id="1911000X"
repo="my-dotfiles"
private_token="XXY_wwwwwx-qQQQRRSSS"
username="gusbemacbe"
declare -a context_dirs=(
"home/.config/Code - Insiders/Preferences"
"home/.config/Code - Insiders/languagepacks.json"
"home/.config/Code - Insiders/rapid_render.json"
"home/.config/Code - Insiders/storage.json"
)
for urlencode in "${context_dirs[@]}"; do
paths=$(jq -nr --arg v "$urlencode" '$v|@uri')
done
for file in "${paths[@]}"; do
curl -sLOJH "PRIVATE-TOKEN: $private_token" "https://gitlab.com/api/v4/projects/$username%2F$repo/repository/files/$file/raw?ref=$branch"
done
But the two conditions for loop output only an encoded path and downloaded only a file.
|
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 urlencode in "${context_dirs[@]}"; do
file=$(jq -nr --arg v "$urlencode" '$v|@uri')
curl -sLOJH "PRIVATE-TOKEN: $private_token" "https://gitlab.com/api/v4/projects/$username%2F$repo/repository/files/$file/raw?ref=$branch"
done
| 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 passing two paramerters but in actual it will vary. I am getting output of these varibales from a command
Below is my code:
FILES="2019_06/
2019_07/"
FILESIZE="100
200"
for file in `cat $FILES`; for filesize in `cat $FILESIZE`
do
do
if [ -n "$file" ] && if [ -n "$filesize" ]
then
echo $file
curl -i -XPOST "http://localhost:8086/write?db=S3check&precision=s" --data-binary 'ecmwftrack,bucketpath=ecmwf-archive/'$file' size=$filesize'
fi
done
done
Could any one pls help me to pass 2 arguments in the for loop at the same time.
Argument should pass like in the for loop
FILES=2019_06 FILESIZE=100
FILES=2019_07 FILESIZE=200
Below is the error message
Kindly help!
Below is my output
Below is my curl coomand
echo curl -i -XPOST "http://localhost:xxxx/write?db=S3check&precision=s" --data-binary 'ecmwftrack,bucketpath=ecmwf-archive/'$files' size='$filesizes''
#!/bin/bash -x
# You said variables get their values from commands, so here
# are stand-ins for those commands:
command_to_get_files(){
aws s3 ls "s3://ui-dl-weather-ecmwf-ireland/ecmwf-archive/"| awk '{print $2}' >>"$FILES"
}
command_to_get_filesizes(){
for file in `cat $FILES`
do
if [ -n "$file" ]
then
# echo $file
s3cmd du -r s3://ui-dl-weather-ecmwf-ireland/ecmwf-archive/$file | awk '{print $1}'>>"$FILESIZE"
fi
done
}
# I assume the values returned from the commands are whitespace delimited
# Therefore it is easy to use command substitution and transform the output
# of the commands into arrays:
files=( $(command_to_get_files) )
filesizes=( $(command_to_get_filesizes) )
|
#!/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 command substitution and transform the output
# of the commands into arrays:
files=( $(command_to_get_files) )
filesizes=( $(command_to_get_filesizes) )
# Repeat this pattern for how ever many parameters you have
# Hat tip to Kamil for idea of using arrays and C-style for loop
for ((i=0; i<"${#files[@]}"; i++)) do
# This printf is a stand-in for what your really want to do
#printf "FILES=%s FILESIZE=%s\n" "${files[$i]%?}" "${filesizes[$i]}"
echo curl -i -XPOST "http://localhost:8086/write?db=S3check&precision=s" --data-binary "ecmwftrack,bucketpath=ecmwf-archive/${files[$i]%?} size=${filesizes[$i]}"
done
The percent sign question mark %? chops off the / that you didn't seem to want.
Put that in a file named myscript.sh then run it:
$ chmod +x myscript.sh
$ ./myscript.sh
FILES=2019_06 FILESIZE=100
FILES=2019_07 FILESIZE=200
Update: Output with printf replaced by echo curl ...:
$ ./myscript.sh
curl -i -XPOST http://localhost:8086/write?db=S3check&precision=s --data-binary ecmwftrack,bucketpath=ecmwf-archive/2019_06 size=100
curl -i -XPOST http://localhost:8086/write?db=S3check&precision=s --data-binary ecmwftrack,bucketpath=ecmwf-archive/2019_07 size=200
| 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 {139..322045}
do
c=0
awk -v var=$c -v j=$j 'NR==j{for(i=10; i<=NF; i++) {if(substr($i,1,3)!="0|0") var++}} END{ print $1 ":" $2 "\t" var }' file.vcf >> out.txt
done
This is the input:
> #<info>
> #..
> # . . .
21 9411245 x C A 505 PASS AC=2 GT:AD:DP:GQ:PL 0|0:11 0|0:12
21 9411246 y C T 505 PASS AC=2 GT:AD:DP:GQ:PL 0|0:11 1|0:13
(the columns are tab separated)
Then I print the 1th and 2th columns linked by : and the count; but it does not work completely, if I use a subset containing only 2 row it works perfectly. This is the result
21:48111872 2
21:48111872 1
21:48111872 0
21:48111872 2
It repeats the rows
How can I fix it ? Thanks in advance, if you fix it please write a short explanation of that.
N.B. it takes a lot of time to compute it (also using for {139..160})
|
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 reading the entire thing for every iteration of the loop. And shell loops are very slow. So you are using a very slow loop and you are needlessly reading thousands of lines in your awk over and over again.
Instead of using a shell loop, just do everything in awk:
$ awk -F"\t" '/^[^#]/{var=0; for(i=10; i<=NF; i++) {if(substr($i,1,3)!="0|0") var++} print $1 ":" $2 "\t" var }' foo.vcf
21:9411245 0
21:9411246 1
Or, a little less condensed:
awk -F"\t" '/^[^#]/{
var=0;
for(i=10; i<=NF; i++) {
if(substr($i,1,3)!="0|0"){
var++
}
}
print $1 ":" $2 "\t" var
}' foo.vcf
Explanation
-F"\t" : set the input field separator to a tab.
/^[^#]/{ ... }: do this only for lines that start (/^a/ will match lines starting with a) with a character that isn't a # ([^#]).
var=0; : set var back to 0 for every input line.
for(i=10; i<=NF; i++) {if(substr($i,1,3)!="0|0") var++} : this is your original code, it counts the number of times it finds a genotype that isn't 0|0.
print $1 ":" $2 "\t" var : again, your code, but now outside the END{} block so it is run on every line and not only the end.
That's it. No shell loop needed and it should take just a few seconds.
| 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: android_arm, windows_x86, linux_x64 etc.
The MYCDEF_VALn can be found from a config.h where we check for
#elif (defined MYCDEF_VALn)
So, I can get all MYCDEF values using gawk -f script1 config.h
script1:
{
if(/defined.*MYCDEF_/)
{
k=index($0, "MYCDEF_");
print substr($0, k, index($0, ")")-k) #all lines of type defined(MYC_DEF_VALn)
}
}
To get all targets, I can read Makefile using gawk -F: -f script2 Makefile
script2:
{if(/^[A-Za-z0-9_]+:$/) print $1}
To build for all MYCDEF_ vals with one target I can pipe the output from first script (using config.h):
gawk -f script1 config.h | xargs -I {} -n 1 make -kj windows_x86 MYCDEF={}
Similarly for all targets with one MYCDEF_val, I can pipe from second script (using Makefile).
gawk -f script2 Makefile| xargs -I {} -n 1 make -kj {} MYCDEF=MYCDEF_VAL1
Now, we want to build with all values of MYCDEF_ for all targets. It can be done using for loop:
for i in $(gawk -f script2 Makefile)
do
gawk -f script1 config.h | xargs -I {} -n 1 make -kj $i MYCDEF={}
done
Is there a oneliner for this?
|
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 i in `ps aux | egrep "[c]ouchpotato|[s]abnzbd|[s]ickbeard|[d]eluge|[n]zbhydra"|awk '{print $2, $11, $12}'`; do echo $i; done
The thing is that as soon as I run the for loop it breaks up the lines I get from awk.
Running
ps aux | egrep "[c]ouchpotato|[s]abnzbd|[s]ickbeard|[d]eluge|[n]zbhydra"|awk '{print $2, $11, $12}'
gives me the result I'm looking for, namely:
27491 /usr/local/couchpotatoserver-custom/env/bin/python /usr/local/couchpotatoserver-custom/var/CouchPotatoServer/CouchPotato.py
27504 /usr/local/deluge/env/bin/python /usr/local/deluge/env/bin/deluged
27525 /usr/local/deluge/env/bin/python /usr/local/deluge/env/bin/deluge-web
27637 /usr/local/nzbhydra/env/bin/python /usr/local/nzbhydra/share/nzbhydra/nzbhydra.py
27671 /usr/local/sabnzbd/env/bin/python /usr/local/sabnzbd/share/SABnzbd /SABnzbd.py
28084 /usr/local/sickbeard-custom/env/bin/python /usr/local/sickbeard-custom/var/SickBeard/SickBeard.py
But adding it to my for loop breaks it into:
27491
/usr/local/couchpotatoserver-custom/env/bin/python
/usr/local/couchpotatoserver-custom/var/CouchPotatoServer/CouchPotato.py
27504
/usr/local/deluge/env/bin/python
/usr/local/deluge/env/bin/deluged
etc...
My goal is for $i to contain the whole line - is this possible? Also, is it possible to use get only the command from $11 and $12? I don't need to have the whole path to python and I don't even need to have the whole path to the application.
Thanks!
|
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 `.....`;do echo "$i"; done
Note: DO NOT quote the backquotes else you shall end up giving to the for loop one big blob of argument,which would be the whole ps's output, and that doesn't do you no good.
HTH
| 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 nullglob. This ensures that file name globbing doesn't expand to the pattern itself if there are no names matching the pattern.
From the bash manual:
nullglob
If set, bash allows patterns which match no files
(see Pathname Expansion above) to expand to a null
string, rather than themselves.
Ps. I wish that the manual used "names" or possibly "filenames" rather than "files".
| 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 script will do what I want:
for i in `find . -type d`
do
pushd $i
./autogen.sh --prefix=/usr && make && sudo make install
popd
done
but, the only problem is that find . -type d shows every directory within this repo, including directories within directories (e.g., it shows tclock/images, that is the images directory, within the tclock directory), when I want just top-level directories (or tclock in the previous example).
|
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 Pink's Haunted Graffiti - Worn Copy (2005)/01
Trepanated Earth.flac ... 17 Jagged Carnival Tours.flac: File name too long
So it appears that inside the loop the $filename variable is equal the names of all FLAC files lumped together.
Of course, omitting quote marks on line 22 results in whitespace problems.
How do I make this work? I'm new to bash and very confused.
|
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 > ls -l Music
total 0
-rw-rw-r-- 1 Arc Arc 0 Mar 14 03:37 foo bar
-rw-rw-r-- 1 Arc Arc 0 Mar 14 03:37 foo bar.flac
-rw-rw-r-- 1 Arc Arc 0 Mar 14 03:37 fubar
-rw-rw-r-- 1 Arc Arc 0 Mar 14 03:37 fubar.flac
now run:
A > for f in Music/*.flac; do echo $f; ls -l "$f" ; done
Music/foo bar.flac
-rw-rw-r-- 1 Arc Arc 0 Mar 14 03:37 Music/foo bar.flac
Music/fubar.flac
-rw-rw-r-- 1 Arc Arc 0 Mar 14 03:37 Music/fubar.flac
| 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 cat. Presumably this is easy to do, but I can't seem to see how on the web.
What I really need is a bash equivalent of the "eval" command in matlab
|
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 variable with a ! inside a curly brace.
For example:
# var=foobar
# varname=var
# echo "${!varname}"
foobar
The downside of this is that it's not POSIX. Meaning it's not guaranteed to be available on all shells. But since the tags on your question included bash, this might be acceptable.
| 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 default.meta to each of the above mentioned folders using the following command.
while read $line;
do
cp -r default.meta $line;
done < test
and when i run the command i get the following error and for the life of it i cannot figure out why this dont work.
cp: missing destination file operand after ‘default.meta’
Try 'cp --help' for more information.
cp: missing destination file operand after ‘default.meta’
Try 'cp --help' for more information.
cp: missing destination file operand after ‘default.meta’
Try 'cp --help' for more information.
cp: missing destination file operand after ‘default.meta’
Try 'cp --help' for more information.
what am i missing here?
|
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=1;
end=1;
for i in {$start..$end}
do
mkdir $i
done
Any suggestion?
|
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 write the outputs of each to the same file.
grep 'bar[0-9]' file.txt | awk '{print $1}'
I have attempted the following but I am not sure exactly where my loops in the script are going wrong.
#!/bin/bash
##Extract ligands from toplist and concatenate to file
for i in /home/ubuntu/Project/working/library_*/Results/list.txt
do
grep 'bar[0-9]' i | awk '{print $1}' | cat ../output.txt i
done
The directory tree is as follows:
.
├── library_1-200
│ ├── Results
│ │ ├── complex
│ │ ├── sorted.txt
│ │ └── list.txt
│ ├── files
│ │ ├── output
│ │ └── txt
│ └── summary.txt
├── library_201-400
│ ├── Results
│ │ ├── complex
│ │ ├── sorted.txt
│ │ └── list.txt
│ ├── files
│ │ ├── output
│ │ └── txt
│ └── summary.txt
├── library_401-600
│ ├── Results
│ │ ├── complex
│ │ ├── sorted.txt
│ │ └── list.txt
│ ├── files
│ │ ├── output
│ │ └── txt
│ └── summary.txt
└── library_601-800
├── Results
│ ├── complex
│ ├── sorted.txt
│ └── list.txt
├── files
│ ├── output
│ └── txt
└── summary.txt
Sample of list.txt, where I just want the Name values put into output.txt
Name Score
bar65 -7.8
bar74 -7.5
bar14 -7.5
bar43 -7.4
bar94 -7.4
bar16 -7.4
bar12 -7.3
bar25 -7.3
bar65 -7.3
bar76 -7.3
bar24 -7.3
bar13 -7.3
bar58 -7.2
bar68 -7.2
bar28 -7.2
Solution was to put "$i" where I previously had just i and to modify to | cat >> ../output.txt
|
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/apache2/sites-available/domain1.tld.conf && a2ensite domain1.tld.conf
sed -i 's/\*\:80/\*\:8080/g' /etc/apache2/sites-available/domain2.tld.conf && a2ensite domain2.tld.conf
sed -i 's/\*\:80/\*\:8080/g' /etc/apache2/sites-available/domain3.tld.conf && a2ensite domain3.tld.conf
sed -i 's/\*\:80/\*\:8080/g' /etc/apache2/sites-available/domain4.tld.conf && a2ensite domain4.tld.conf
mkdir -p /etc/systemd/system/varnish.service.d # Be aware! You might not need this in the future.
cat <<-'VARNISH' > /etc/systemd/system/varnish.service.d/customexec.conf
[Service]
ExecStart=
ExecStart=/usr/sbin/varnishd -j unix,user=vcache -F -a :80 -T localhost:6082 -f /etc/varnish/default.vcl -S /etc/varnish/secret -s malloc,256m
VARNISH
systemctl restart apache2.service && systemctl daemon-reload && systemctl restart varnish.service
This code segment seems quite "heavy", especially the repetitiveness of the sed operations regarding domain.tld.
This get's even "heavier" because I have a code segment which is similar in length that uses to me uninstall varnish and revert all changes just in case of desire.
My question:
What strategy will you take to make the installation script shorter in general (at least less rows, maybe also less commands), and in particular, to lower amount of sed operations.
Notes:
I would assume that the first thing to do is to somehow unify ports.conf, 000-default.conf, and each .conf file of each site, all into one operation. Maybe via a for loop on /etc/apache2/ports.conf/ && /etc/apache2/sites-available/*/.
|
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 {/} ::: /etc/apache2/sites-available/*
mkdir -p /etc/systemd/system/varnish.service.d # Be aware! You might not need this in the future.
cat <<-'VARNISH' > /etc/systemd/system/varnish.service.d/customexec.conf
[Service]
ExecStart=
ExecStart=/usr/sbin/varnishd -j unix,user=vcache -F -a :80 -T localhost:6082 -f /etc/varnish/default.vcl -S /etc/varnish/secret -s malloc,256m
VARNISH
systemctl restart apache2.service && systemctl daemon-reload && systemctl restart varnish.service
| 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
count=0
fi
done
if [ $count != 0 ]; then
wait
fi
| 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_process_copy.py
run_mcmc=1
n_samples=1000
n_thin=100
nu=3.
mu=1.
sig=1.
start_data_file=\"data_file
end_data_file=.txt\"
seed=1
alpha=1.
for i in "10. 1" "1. 2" "0.1 3" "0.01 4"; do # i is alpha, num
IFS=' ' read -a myarray <<< "$i"
alpha=${myarray[0]}
num=${myarray[1]}
data_file=$start_data_file$num$end_data_file
echo $data_file
if [ $run_mcmc == 1 ]; then
sed -i "s/nnn/$n_samples/g" student_t_sampler_copy.c # set number of samples, 1000
sed -i "s/ttt/$n_thin/g" student_t_sampler_copy.c # set thinning, 5
sed -i "s/nununu/$nu/g" student_t_sampler_copy.c # set nu
sed -i "s/mumumu/$mu/g" student_t_sampler_copy.c # set mu
sed -i "s/sigsigsig/$sig/g" student_t_sampler_copy.c # set sig
sed -i "s/fff/$data_file/g" student_t_sampler_copy.c # data file
sed -i "s/sss/$seed/g" student_t_sampler_copy.c # set seed
sed -i "s/aaa/$alpha/g" student_t_sampler_copy.c # set alpha
make ./student_t_sampler_copy
./student_t_sampler_copy
fi
n_bins=100
# echo "$data_file"
sed -i "s/fff/$data_file/g" post_process_copy.py # set data file in python
sed -i "s/bbb/$n_bins/g" post_process_copy.py # set number of bins
sed -i "s/aaa/$alpha/g" post_process_copy.py # set set in plot title
sed -i "s/iii/$num/g" post_process_copy.py # set set in plot title
python post_process_copy.py
done
wait # wait for all processes to finish
The output is as follows
"data_file1.txt"
gcc -I/usr/include -L/usr/local/lib student_t_sampler_copy.c -o student_t_sampler_copy -lgsl -lgslcblas -lm
"data_file2.txt"
gcc -I/usr/include -L/usr/local/lib student_t_sampler_copy.c -o student_t_sampler_copy -lgsl -lgslcblas -lm
"data_file3.txt"
gcc -I/usr/include -L/usr/local/lib student_t_sampler_copy.c -o student_t_sampler_copy -lgsl -lgslcblas -lm
"data_file4.txt"
gcc -I/usr/include -L/usr/local/lib student_t_sampler_copy.c -o student_t_sampler_copy -lgsl -lgslcblas -lm
So even though it echos the correct data file, both python and c only receive data_file1.txt
|
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 file within the loop (immediately after the for).
| 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 but i am unable to set the condition for the same. I want to lint all python files but this code exits after linting a single python file. Is it possible to make a check and if the exit code is something like an error it should terminate else the linting must proceed.
Pylint has different exit codes for error and warning but i am not able to set a condition for this : pylint exit code
This is the workflow which I have used :
---
name: Python Notebooks Linting
on:
push:
branches:
- 'main'
repository_dispatch:
# types: [python-lint] test
jobs:
linting:
runs-on: ubuntu-latest
steps:
- name: Checkout the code
uses: actions/checkout@v2
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install pylint
pip install umsgpack
pip install cryptography
pip install pylint-fail-under
- name: pylint version
run: pylint --version
- name: Analysing the code with pylint
run: |
set -e
for file in **/*.py; do pylint "$file"; done
But this code exits after linting a single file I want to set a condition that the linting should exit if the exit code is a specific number. How do I implement this ?
|
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 python file and fails if pylint score is less than 6.0
run: |
for file in $(find -name '*.py')
do
pylint --disable=E0401,W0611 "$file" --fail-under=6.0;
done
Refer : Lint python files using Github Workflows
| 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 some cases I get a negative output and I don't see how that can happen.
For example
./script1.sh 3706907995955475988644380 25
outputs
-2119144605827694052
My script:
#!/bin/bash
sum=0
value=$1
arr=()
for ((i = 0; i < ${#value}; i++)); do
arr+=(${value:$i:1})
done
for x in "${arr[@]}"; do
sum=$(($sum+(x**$2)))
done
echo $sum
|
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:
#!/bin/bash
num1=$1
num2=$2
sum=0
for (( i=0; i<${#num1}; i++ )); do
n=${num1:$i:1}
sum=$( bc <<<"$sum + $(bc <<<"${n}^$num2")" )
done
echo "$sum"
| 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 RHEL 5.0 server.
| 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 specified in the array, like this:
./folderX
./folderA/emty_file1
./folderA/emty_file7
./folderA/emty_file12
./folderA/emty_file24
How can I make the script also detect empty files in the other directories specified in the array?
|
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 want to rename each *.png* file to its product name, without the UPC numbers, using its current filename matched to the strings in the text file---so instead of 052100029962.png I would have mccormickkeeper.png. This has been surprisingly difficult; I have tried varieties of the following and with no success.
for f in $(find . -iname "*.png"); do
while read -r line; do
if [[ "$f" == *"$line"* ]]; then ## also tried =~
cp "$f" "$line";
fi
done < upcs.txt
done
By "varieties," I mean switching the order of operations, e.g., putting the while loop before the for loop, and even creating another text file with only product names so that I could read and compare them also. For the latter, I did:
for f in $(find . -iname "*.png"); do
while read -r line; do
if [[ "$f" == *"$line"* ]]; do
while read -r line2; do
cp "$f" "$line2";
done < upcs_names_only.txt;
fi;
done < upcs.txt;
done
I even tried putting the 2nd while loop before calling the if loop.
Lastly, I know that even if formulated correctly, the above loops would not retain the .png extension. To deal with this, I was prepared to select the results manually and add .png.
What am I doing wrong? Can anyone help me better understand the logic too?
|
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 echo after testing. Of course I assume your first field is always a sequence of digits and the second field has no whitespaces, does not start with a digit, etc.
If you need any additional actions, like for example to check for duplicated target names, you can do it on the file at first place. Or if you need, in any case mv not to overwrite an existing target, use -n (--no-clobber), also -i (--interactive) would prompt for user input for the same reason.
| 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, it prints
You chose
> first
second
third
Why is that, and how do I fix this?
|
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 process substitution. The readarray utility will by default read individual lines, i.e. strings of text terminated by a newline, and the -t option makes the utility remove the terminating newline from the data that is read.
The printf call prints each array element with a leading > and space.
Giving multiple arguments to printf, which you do by giving it the expansion of an array like this, it will reuse its formatting string for outputting each individual argument. This means there is no need for a loop.
The issue with your script is that you are reading the output from your Python script into a single string. The command substitution $( python3 test.py ) would be expanded to a string that you then would have to manually parse and split on newlines into the correct array elements.
You could do as Dabombber suggests and let the shell do this splitting for you with choice=( $( python test.py ) ) (the declare -a is not needed), but note that this would split the string on any whitespace (spaces, tabs and newlines (the contents of $IFS) by default), which may not be what you want if you want your individual array elements to include spaces.
An option then would possibly be to set IFS to a newline to get the shell to split the data on newlines only, or to read the output for the Python code with read, and these may be good solutions, but you have the readarray built-in utility in bash which makes this easier.
It looks (judging from the variable name and other text in your code) that you may want to implement some sort of interactive menu.
This could also be done with select in bash:
readarray -t options < <( python3 test.py )
echo 'Please select your option' >&2
PS3='Your selection: '
select ch in "${options[@]}"; do
[ -n "$ch" ] && break
echo 'Invalid, try again' >&2
done
printf 'You chose option %d ("%s")\n' "$REPLY" "$ch"
This would use the output of your Python script as options in a select loop. The loop would continue until a valid option has been selected by the user. At the end, the picked option (and its number) is printed.
The PS3 prompt is the prompt used by select in bash. The default value is #? followed by a space.
| 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 -type d | grep -v \\.$ | awk -F'./' '{print $2}'
But within a ksh for loop, the first is working unlike the second ...
Why ? :
(workaround:
for dir in `find . -maxdepth 1 -type d -exec echo "{}" \; | awk -F'/' {print $2}`
do
echo "dir: $dir"
done
will work)
This also works:
for dir in `ls -l | awk '{print $9}' | grep 'dirsPrefix*'`
do
echo "dir: $dir"
done
But this does not:
for dir in `find . -maxdepth 1 -type d | grep -v \\.$ | awk -F'./' '{print $2}'`
do
echo "dir: $dir"
done
|
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 output like for i in "$(ls -1Atu)";, I'll get a single iteration, and $i will contain the output from ls entirely.
How can we solve this problem? I should note that any variants with ls -1Atu preferable, as I need, what would the resulting files were sorted by atime.
Thank you
|
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 support file names that contain newlines; this is a fundamental limitation of ls¹.
Furthermore, and this is what you ran against, setting IFS has no effect on the other thing that happens on the expansion of a command substitution, which is globbing (wildcard matching). You can turn off globbing, and then your script will work as long as file names don't contain newlines.
IFS='
'
set -- *"$IFS"*
if [ -e "$1" ]; then
echo >&2 "There are file names with newlines. I cannot cope with this."
exit 2
fi
set -f
for i in $(ls -1Atu); do
printf '%s\n' "$i"
done
set +f
unset IFS
The easy, reliable way to enumerate files by date is to use something other than a pure Bourne-style shell, such as zsh which has glob qualifiers to modify the way wildcard matches are sorted.
#!/bin/zsh
files_by_access_time=(*(Doa))
¹ You can work around it with some ls implementations, but not if you need portability.
| 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 ..
done
The above code I want to be executed in every directory under a.
|
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
done
|
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 does my shell script choke on whitespace or other special characters? (these two as per Stéphane Chazelas' suggestion)
on stackoverflow or here.
In your case:
grep -A1 -- "$i" final.contigs.fa >> gene.fa
should do the trick (here also adding a -- to guard against values of $i that would start with -).
| 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 to save that number of line first in a variable outside the loop:
n=$(wc -l < sedtest1) # using redirection avoids the output containing the filename
for ((a = 0; a < n; a++)); do echo "$a"; done
I also suspect that you're trying to use a loop to process text in an inefficient and non-shell way. You may want to read Why is using a shell loop to process text considered bad practice?. Looping over each line of a file in that way is not the right way to go.
| 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 then replace $seq start with 1.
This is the file i want.
{
name: customer 1
id: 1
}
{
name: customer 2
id: 2
}
{
name: customer 3
id: 3
}
While reading first line, the ID should be 1, while reading second line the ID should be 2`
|
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, *.amb or *.bmb or *.cmb that particulal IF should execute:
cd /tmp/test
find */ -type f -exec ls {} \; > /tmp/test/list1
for file in `cat /tmp/test/list1`
do
if [ -f *.amb ]
then
sed "s/amb/amx/g" /tmp/test/list1 > /tmp/test/list2
ls /tmp/test/list2 >> /tmp/test/finallist
fi
if [ -f *.bmb ]
then
sed "s/bmb/bmx/g" /tmp/test/list1 > /tmp/test/list2
ls /tmp/test/list2 >> /tmp/test/finallist
fi
if [ -f *.cmb ]
then
sed "s/cmb/cmx/g" /tmp/test/list1 > /tmp/test/list2
ls /tmp/test/list2 >> /tmp/test/finallist
fi
done
echo "*********************"
echo -e "\nFinal list of files after replacing from tmp area"
felist=`cat /tmp/test/finallist`
echo -e "\nfefiles_list=`echo $felist`"
So my final output should be:
amx/eng/canon.amx
bmx/eng/case.bmx
cmx/eng/hint.cmx
|
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//cmb/bmx}") ;;
esac
done <( cd /tmp/test && find */ -type f -print0 2>/dev/null )
printf '*********************\n\n'
printf 'Final list of files after replacing from tmp area\nfefiles_list=%s\n' "${finallist[*]}"
Incidentally,
find */ -type f -exec ls {} \; > /tmp/test/list1 could better be written as find */ -type f -print > /tmp/test/list1, and since you've tagged with linux even that than be reduced further to find */ -type f > /tmp/test/list1. But this will break on strange (but legal) filenames.
Backticks are deprecated and you should be using $( … ) instead. But even that will break with filenames containing spaces and other special characters.
| 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 chrom in `seq 1 22` X Y
do
samtools view -bh $filename $chrom > $path/$chrom.bam
samtools index > $path/$chrom.bam;
done
done
However, I get many messages of this kind: "split.sh: line 12: /mypath/MAP-9-[0-9][0-9][0-9]/6.bam: No such file or directory"
The problem is that the script is not recognizing the "[0-9][0-9][0-9]" regex part of the pathname. I also tried adding escape characters to the square brackets without success. It must be a very simple solution, but I am not able to solve it.
This is an extract of the tree command's output:
|-- [[
|-- MAP-9-001
| |-- MAP-9-001.bam
| `-- MAP-9-001.bam.bai
|-- MAP-9-003
| |-- MAP-9-003.bam
| `-- MAP-9-003.bam.bai
|-- MAP-9-005
| |-- MAP-9-095.bam
| `-- MAP-9-095.bam.bai
|-- split.sh
|
/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 instead is to generate each output file from the corresponding loop variable $filename, as follows:
#!/bin/bash
shopt -s nullglob
for filename in /mypath/MAP-9-[0-9][0-9][0-9]/*.bam; do
[ -e "$filename" ] || continue
echo "$filename"
for chrom in {1..22} X Y; do
samtools view -bh "$filename" "$chrom" > "${filename%/*}/${chrom}.bam"
samtools index > "${filename%/*}/$chrom.bam"
done
done
The shell parameter expansion ${filename%/*} expands to the value of $filename with the shortest trailing substring /* removed; it thus gives you the dirname of each input file, to which you can then add the $chrom.bam to form each output file in turn.
| 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, thank you.
There are no prefixes, 000 is the whole name. There is no file labeled 021.
|
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 whole file is a number, then zmv -f -n '<->(#qnOn)' '${(l[3][0])$((MATCH+1))}' would be enough, or <0-20> instead of <-> to rename only the ones from 0 to 20, or <0-20>~^[0-9](#c3) for the ones from 0 to 20 expressed on 3 digits).
The replacement is computed using the ksh-style ${var//pattern/replacement}, with the pattern being (#m)<->, (#m) to trigger the capture of what's matched in $MATCH and <-> matches any sequence of decimal digits (the bound-less form of <3-12>). The l[width][pad] left-padding parameter expansion flag is used for padding.
We sort the file list in reverse numeric Order of their name with the n and On qualifiers to make sure file002 is renamed to file003 before file001 is renamed to file002.
The -f disables the sanity checks which here would complain about some destinations being also found in the sources, though that means that it won't prevent data loss if there's both a file1 and file01 files for instance.
If you don't have zsh, but have bash and files named 000 to 020 exist and are the ones you want to rename as you later clarified, you can do:
for file in {020..000}; do
printf -v new %03d "$(( 10#$file + 1 ))"
mv "$file" "$new"
done
(bash did copy {020..000} from zsh actually, while zsh copied -v from bash, that code would work in both shells; the 10# and quotes are not necessary in zsh).
Here, as the file names are very tamed, you can also do things like:
ls -rq | LC_ALL=C awk '
/^[0-9]{3}$/ && $0 <= 20 {
printf "mv %s %03d\n", $0, $0+1
}' | sh
-q (standard though not currently supported by busybox ls) to make sure there's one filename per line even if there are files with newlines in their name. LC_ALL=C so [0-9] only matches 0123456789. If your awk is mawk, replace [0-9]{3} with [0-9][0-9][0-9].
| 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 string in the middle of the path.
My command is locate --regex ^.*\\.original$ that works perfectly in terminal. It finds all files that ends with the .original suffix such as file.original
However when I use the same command in bash script in the for loop it returns me variants such as file.original file-original file_original etc.
How should I modify the regex or for loop to get only .original files?
My shell is:
$ echo $BASH
/usr/bin/bash
My bash script is:
#!/usr/bin/bash
echo "Plain locate command:"
locate --regex ^.*\\.original$ | grep test
echo "For loop:"
for file in `locate --regex ^.*\\.original$ | grep test`; do
echo $file
done
You can use this for testing:
mkdir /tmp/test
touch /tmp/test/file.original
touch /tmp/test/file-original
touch /tmp/test/file_original
updatedb
locate --regex ^.*\\.original$
In my terminal it will find:
/tmp/test/file.original
But my script will find:
Plain locate command:
/tmp/test/file.original
For loop:
/tmp/test/file-original
/tmp/test/file.original
/tmp/test/file_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.
Change the relevant line to:
for file in $(locate --regex '^.*\.original$' | grep test); do
Notes:
I used single-quoting to conveniently handle the backslash and the asterisk. In your original code the unquoted and unescaped asterisk can trigger the filename expansion.
^.* in the regex changes nothing. Single-quoted \.original$ would be enough. I decided to keep ^.* only to point out the possibility of filename expansion.
Get used to quoting variables (e.g. echo "$file"). The linked answer recommends quoting $() as well, but in our for loop quoting would be wrong. Not quoting $() is also wrong. Both are wrong because…
In general building for loops like this is often wrong. It's the Bash pitfall number one. To do something with the output of locate better pipe it to xargs, preferably as null-terminated strings:
locate -0 … | grep -z … | xargs -r0 …
These options are not portable.
| 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 ); 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 ); done
root@kali-linux:~/Softwares/Softwares/Tools/dirsearch# for i in 1 2 3 4; do
> array=( "${array[@]}" "$i" )
> done
root@kali-linux:~/Softwares/Softwares/Tools/dirsearch# echo $array
1
root@kali-linux:~/Softwares/Softwares/Tools/dirsearch#
How to add/remove an element to/from the array in bash? I tried to add like as said in this question still it doesnt work and print 1
|
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 of indice 0 or an empty string if it's not set).
To expand to all the elements of the array, you need:
$ printf ' - "%s"\n' "${array[@]}"
- "1"
- "2"
- "3"
- "4"
For the first element of the array (which may not be the one with indice 0 as ksh/bash arrays are sparse):
$ printf '%s\n' "${array[@]:0:1}"
1
And for the element of indice 0 (which in your example is going to be the same as the first element):
$ printf '%s\n' "$array"
1
or:
$ printf '%s\n' "${array[0]}"
1
To print the definition of a variable, you can also use typeset -p:
ksh93u+$ typeset -p array
typeset -a array=( 1 2 3 4 )
bash-5.0$ typeset -p array
declare -a array=([0]="1" [1]="2" [2]="3" [3]="4")
bash-5.0$ unset 'array[0]'
bash-5.0$ typeset -p array
declare -a array=([1]="2" [2]="3" [3]="4")
bash-5.0$ printf '%s\n' "$array"
bash-5.0$ printf '%s\n' "${array[@]:0:1}"
2
| 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 loop to start the scripts in sequential order?
|
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, as originally posted), otherwise the shell will produce an error message.
Also, as pointed out by Stéphane Chazelas, you should make a habit of quoting variable expansions (where approproate, which is in most places); a good introduction can be found here.
| 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 directory, do some stuff, and cd back out, which I realize I can probably do the equivalent with some string concatenation but this behavior is so baffling to me and I couldn't find any other questions on it so I thought I would ask.)
|
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 of ls is enclosed in quotes, so therefore it is treated as one single argument, causing the for loop to iterate only once, with the entire output ls as an argument. Your code dutifully prints the entire output of ls twice.
Rather than using ls, a better way to construct your example would be:
find . -type d -maxdepth 1 -mindepth 1 -exec printf '%s\n%s\n' "{}" "{}" \;
| 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 with no problems however when I run it here, I get:
sed: -e expression #1, char 9: unterminated `s' command
What am I doing wrong?
|
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 "Choose object from the list below\n"
printf "**policy**\n**ipadd**r\n**subnet**\n**netmap**\n**netgroup**\n
**host**\n**iprange**\n**zonegroup**\n" | tee object.txt
read object
IFS="`printf '\n\t'`"
# Find all selected object names that contain spaces
cf -TJK name "$object" q | tail -n +3 |sed 's/ *$//' |grep " " >temp
for x in `cat temp`
do
# Assign the y variable to the new name
y=`printf "$x" | tr ' ' '_'`
# Rename the object using underscores
cf "$object" modify name="$x" newname="$y"
done
|
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 "$object" ]] && break
done
if [[ "$object" == "all" ]]; then
# comma separated list of all objects
object=$( IFS=,; echo "${objects[*]}" )
fi
cf -TJK name "$object" q | etc etc etc
# ...........^ get into the habit of quoting your variables.
I'm assuming bash here. Let us know if that's not the shell you're using.
If you're stuck in a shell without arrays, you can do this since the objects are simple words:
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 # $objects is specifically not quoted here ...
[ -n "$object" ] && break
done
if [ "$object" = "all" ]; then
object=$( set -- $objects; IFS=,; echo "$*" ) # ... or here
fi
cf -TJK name "$object" q | etc etc etc
| 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
26181/java
26181/java
26181/java
26181/java
26181/java
26181/java
26181/java
Works ok if i add single quote and in awk condition /XXX.XXX.XXX.XXX/ i give static value it will print 7th column
But if i use Double quotes and /$i/ variable
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 "/$i/ {print $7}";done
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:62778 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:35708 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:40920 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:40918 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:31211 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:35708 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:40920 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:40918 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:31211 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:35708 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:40920 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:40918 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:31211 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:35708 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:40920 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:40918 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:31211 ESTABLISHED 26181/java
When it should only be printing column 7. What i'm missing here
|
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 probably pass $i into awk using -v variable="$i" and use variable to match() against the lines (or use ~ as αғsнιη shows).
| 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, & Success Success.wav.mp3
There four types of love.wav.mp3
Theres too much love to let you fail.wav.mp3
|
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 could also do a literal substitution with "${i/.wav/.mp3}".
| 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 behaviour as with the "$@" parameter expansion of the Bourne shell, or the "${array[@]}" of the Korn shell where elements are passed separate and verbatim as if quoted including empty ones)
${a:^b} is an array zipping parameter expansion operator. There's also the ${a:^^b} variant which reuses elements of the shorter array if the arrays don't have the same number of elements.
In zsh, best is to avoid dereferencing array elements via their index if possible as that is very inefficient in current versions especially for large arrays, mainly because of the fact zsh doesn't record the size of its arrays, so even though accessing the nth element should be instantaneous as that's indexing in a C array, zsh still needs to check n is not past the end of the arrays for which it still needs to check the n - 1 elements before it.
For looping over 3 or more arrays, you still need to do that though:
n=$#var1
for (( i = 1; i <= n; i++ ))
printf '%q, %q, %q\n' "$var1[i]" "$var2[i]" "$var3[i]"
Which would be orders of magnitudes slower than the equivalent code in ksh93 or even bash.
n=${#var1[@]}
for (( i = 0; i < n; i++ )) {
printf '%q, %q, %q\n' "${var1[i]}" "${var2[i]}" "${var3[i]}"
}
| "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 does not work. I tried nailing down the error and if I run this
for f in $(ls); do test -L $f && echo "$f is a valid symlink"; done
no output is produced, despite existing and valid symlinks. If I run the same command with $f replaced with the actual file name, it works. Also f=filename; test -L $f && echo "$f is a valid symlink"; works as expected, so the problem seems to be the loop.
What am I missing?
|
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 the wiser.
Use a glob instead:
for f in *; do test -L "$f" || continue; test -e "$f" || echo "$f deadlink"; done
See How can I find broken symlinks for other possible solutions to your underlying problem.
| 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 failed a task have to be moved to users/failed/failedusers
what i am currently doing is i am creating a new file first using
cat failed | awk -F ":" '/FAILED/ {print $1}' | uniq > failedusers
and then i move the folders using the following command
while read line; do cp -r users/$line users/failed; done < failedusers
My question here is can i do the same using just the for command instead of writing the output to another file and using the while read command to get it done?
for example somehow assign a value to a variable in a loop like
faileduser=`cat failed | awk -F ":" '/FAILED/ {print $1}' | uniq`
and then write something like
mv users/$faileduser user/failed/$faileduser
i am getting all kinds of errors when i am trying to write something like above.
thanks
|
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
zargs -rI USER -- $faileduser -- cp -r users/USER user/failed/USER
Assuming you want to copy USER to user/failed/USER, that is, copy it into user/failed, you could also do (still with zsh):
(( $#faileduser )) && cp -r users/$^faileduser user/failed/
With the bash shell, you could do something similar with:
readarray -t faileduser < <(awk -F : '/FAILED/ {print $1}' failed | sort -u)
(( ${#faileduser[@]} )) &&
cp -r "${faileduser[@]/#/user\/}" user/failed/
Or get awk to prepend the user/ to all the user names:
readarray -t faileduser < <(awk -F : '/FAILED/ {print "user/"$1}' failed | sort -u)
(( ${#faileduser[@]} )) &&
cp -r "${faileduser[@]}" user/failed/
With a for loop, with Korn-like shells (including bash, and would also work with zsh) the syntax would be:
for user in "${faileduser[@]}"; do
cp -r "user/$user" "user/failed/$user"
done
Which in zsh could be shortened to:
for user ($faileduser) cp -r user/$user user/failed/$user
With:
faileduser=`cat failed | awk -F ":" '/FAILED/ {print $1}' | uniq`
(`...` being the archaic and deprecated form of command substitution. Use $(...) instead).
You're storing awk's output in a scalar, not array variable.
In zsh, you can split it on newline with the f parameter expansion flag like we do directly above on the command substitution:
array=( ${(f)faileduser} )
In bash (or ksh), you could use the split+glob operator after having disabled glob and tuned split:
set -o noglob
IFS=$'\n'
array=( $faileduser )
(yes, in bash, leaving a parameter expansion unquoted invokes an implicit split+glob operator (!), a misfeature inherited from the Bourne shell, fixed in zsh and most modern non-Bourne-like shells).
| 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' \
--header 'Authorization: Bearer XXXXX' \
--data-urlencode 'XXID=`find * -name $i`'
done
I get a response
{"code":"400-bad-request","message":"XX app with ID `find * -name $i` not found"}
How do i put in the value from $i that i captured earlier into this --data-urlencode field?
My id file is very simple, it contains a few numbers like below.
1234
23232
32323
any help is highly appreciated. Thanks.
This is my id file. It is basically a list of numbers
1761
1762
1763
1764
1765
So my ultimate aim is to go in a loop where the first curl request will go --data-urlencode 'XXID=1761' second request will go --data-urlencode 'XXID=1762', third goes --data-urlencode 'XXID=1763' etc
|
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:/myurla \
--header 'X-XX-Authorization: XX' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'ACS-Licensing-Ack: XXXX' \
--header 'Authorization: Bearer XXXXX' \
--data-urlencode XXID="$line"
done
If your id file only contains a number which is increasing by 1 every line, you could use a seq of {..} to create a sequence of numbers:
for num in {1761..1765}
do
echo $num
done
for num in $(seq 1761 1765)
do
echo $num
done
| 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 perform the task and then move to the next line. I've saved my values into example.txt and tried the following but it didn't work:
for n in [ test1.txt | wc -l ]
do
test1.txt$2 + test1.txt$3 > test1.txt$4
done
|
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 (in bash):
$ while read -a vals; do
vals+=( $((vals[1] + vals[2])) )
printf '%d %d %d %d\n' "${vals[@]}"
done < test1.txt
1 2 3 5
4 5 6 11
7 8 9 17
(but don't do that, either).
| 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 itrpl_dsm_12_5.tif itrpl_dsm_2_5.tif itrpl_dsm_4_5.tif itrpl_dsm_6_5.tif itrpl_dsm_8_5.tif
itrpl_dsm_10_4.tif itrpl_dsm_12_6.tif itrpl_dsm_2_6.tif itrpl_dsm_4_6.tif itrpl_dsm_6_6.tif itrpl_dsm_8_6.tif
itrpl_dsm_10_5.tif itrpl_dsm_12_7.tif itrpl_dsm_2_7.tif itrpl_dsm_4_7.tif itrpl_dsm_6_7.tif itrpl_dsm_8_7.tif
itrpl_dsm_10_6.tif itrpl_dsm_12_8.tif itrpl_dsm_2_8.tif itrpl_dsm_4_8.tif itrpl_dsm_6_8.tif itrpl_dsm_8_8.tif
itrpl_dsm_10_7.tif itrpl_dsm_1_1.tif itrpl_dsm_3_1.tif itrpl_dsm_5_1.tif itrpl_dsm_7_1.tif itrpl_dsm_9_1.tif
itrpl_dsm_10_8.tif itrpl_dsm_1_2.tif itrpl_dsm_3_2.tif itrpl_dsm_5_2.tif itrpl_dsm_7_2.tif itrpl_dsm_9_2.tif
itrpl_dsm_11_1.tif itrpl_dsm_1_3.tif itrpl_dsm_3_3.tif itrpl_dsm_5_3.tif itrpl_dsm_7_3.tif itrpl_dsm_9_3.tif
itrpl_dsm_11_2.tif itrpl_dsm_1_4.tif itrpl_dsm_3_4.tif itrpl_dsm_5_4.tif itrpl_dsm_7_4.tif itrpl_dsm_9_4.tif
itrpl_dsm_11_3.tif itrpl_dsm_1_5.tif itrpl_dsm_3_5.tif itrpl_dsm_5_5.tif itrpl_dsm_7_5.tif itrpl_dsm_9_5.tif
itrpl_dsm_11_4.tif itrpl_dsm_1_6.tif itrpl_dsm_3_6.tif itrpl_dsm_5_6.tif itrpl_dsm_7_6.tif itrpl_dsm_9_6.tif
itrpl_dsm_11_5.tif itrpl_dsm_1_7.tif itrpl_dsm_3_7.tif itrpl_dsm_5_7.tif itrpl_dsm_7_7.tif itrpl_dsm_9_7.tif
itrpl_dsm_11_6.tif itrpl_dsm_1_8.tif itrpl_dsm_3_8.tif itrpl_dsm_5_8.tif itrpl_dsm_7_8.tif itrpl_dsm_9_8.tif
itrpl_dsm_11_7.tif itrpl_dsm_2_1.tif itrpl_dsm_4_1.tif itrpl_dsm_6_1.tif itrpl_dsm_8_1.tif
itrpl_dsm_11_8.tif itrpl_dsm_2_2.tif itrpl_dsm_4_2.tif itrpl_dsm_6_2.tif itrpl_dsm_8_2.tif
When executing
ubuntu@ip-172-31-8-46:~/backup$ for (( i=1; i<=12; i++ )); do tar -czvf itrpl_dsm_$i.tar.gz itrpl_dsm_$i_*.tif; done
Output:
itrpl_dsm_10_1.tif
itrpl_dsm_10_2.tif
itrpl_dsm_10_3.tif
itrpl_dsm_10_4.tif
itrpl_dsm_10_5.tif
itrpl_dsm_10_6.tif
itrpl_dsm_10_7.tif
itrpl_dsm_10_8.tif
itrpl_dsm_11_1.tif
itrpl_dsm_11_2.tif
itrpl_dsm_11_3.tif
itrpl_dsm_11_4.tif
itrpl_dsm_11_5.tif
itrpl_dsm_11_6.tif
itrpl_dsm_11_7.tif
itrpl_dsm_11_8.tif
itrpl_dsm_12_3.tif
itrpl_dsm_12_4.tif
itrpl_dsm_12_5.tif
itrpl_dsm_12_6.tif
itrpl_dsm_12_7.tif
itrpl_dsm_12_8.tif
My intention was generating itrpl_dsm_1.tar.gz from itrpl_dsm_1_*.tif files, but apparently it didn't do what I want.
|
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 and it will be replaced by every file matching the pattern.
| 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 contains this: (please note dummy data) and its a sample
Barrera|Wilkinson|(09) 1466 1886|[email protected]
Hopkins|Sellers|(07) 3814 2364|[email protected]
Hunter|Calderon|(01) 3984 0139|[email protected]
Does anyone have any insight as to why the for loop isn't returning what I am aiming for?
|
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 value of column 2: 9 (line 1)
Longest value of column 3: 14 (line 1)
Longest value of column 4: 26 (line 2)
This script will, for every line, loop over all fields (from 1 to NF, the number of fields) and see if the length of the field (temporarily stored in a variable l) is greater than the longest length found so far, which is stored in an array variable lval under the index of the field (=column) number.
On the first line, lval is not yet initialized, and it will behave as if all lval[i] were 0 (in reality, it is more complex than that).
If the length of the field i on the current line is longer than the value stored in lval[i], the script will store the current length of the field in lval[i] and the current line number (which is accessible through the "automatic" variable FNR) into the array variable lpos.
At the end of the file (END condition), it will print the longest length and corresponding position for all columns. I use the construct for (i in lval) which loops over all indices present in the array lval, so I don't have to save the number of columns in an extra variable (as would be necessary for something like for (i=1;i<=ncols;i++) - in the END block, the concept of "number of fields" becomes somewhat ill-defined although in practice awk will often use the corresponding values for the last line of the file when accessed).
Note that it is rarely necessary to call awk in a shell loop; it can do most of the things you would need a loop for by itself.
As for the reason why your original attempt failed, you are trying to feed a shell variable ($i) to an awk script whose code is enclosed in single quotes (as is recommended), but the single quotes turn off the interpretation of shell variables (and even if not, it would not have worked like that).
| 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 'output' has the same text as 'book'.
The code :
for word in {am pm cm words count ......}
do
sed -i 's/${word}//g' book
done
do you have any idea why the words in the list aren't deleted as they should?
|
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 | cut -f 1 -d \.; done`
for i in $list; do cat $i.rem.1.fq $i.rem.2.fq > $i.rem.b.fq; done
Can I do this without making a list? What does the cut -f 1 -d do? And why does cat $i.rem.1.fq work but not cat $i.1.fq if the the rem part of the file name is in between the two * on the list? Does that mean it captures everything before *rem* (e.g. file1)?
|
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 in the question is error-prone – if a file contained a space, the second for loop might not function correctly.
cut -f 1 -d. cuts a string into fields (delimited in this case by .), and outputs the requested fields (in this case, just the first). If given the string file 1.whatever, it would output file 1. Again, this is error prone given the glob pattern *rem*.1.fq could return filenames with anyremthing.1.fq – the * wildcard matches anything (including nothing).
A better option is to do a single loop and use a parameter expansion, with some form of substitution inside the loop to match other files with relevant names.
Above, the glob pattern *.rem.1.fq is used – you may wish to narrow this down further – eg. file[0-9].rem.1.fq.
${param%string} is used in the loop to remove the suffix .1.fq. Many shells also support other forms of parameter expansion substitutions – eg. ${param/string/repl}.
Also it's generally a good idea to quote all "$param" or "$(command)" substitutions – otherwise most shells will apply field splitting and filename generation and you might end up trying to cat file 1 instead of cat 'file 1', for example.
Also don't forget the -- to mark the end of options if you can't guarantee file names won't start with -.
| 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 "Hello $i" $j
done
this should work as
echo "Dear john, email text" | mail -s "Hello john" [email protected]
Also if I want to create this list in a separate csv file, how will I use that? E.g
name, email
john, [email protected]
jenny, [email protected]
doe, [email protected]
|
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:
while IFS=, read -r i j; do
echo "Dear $i, email text" | mail -s "Hello $i" "$j"
done < file.csv
(this assumes your file is correctly formatted CSV, without a header line).
| 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 when i start my script with "set -x" i see this:
+ for LINE in '`cat file`'
+ /opt/cprocsp/bin/amd64/certmgr -inst -cont ''\''\\.\Aktiv'
Error
+ for LINE in '`cat file`'
+ /opt/cprocsp/bin/amd64/certmgr -inst -cont Co.
Error
+ for LINE in '`cat file`'
+ /opt/cprocsp/bin/amd64/certmgr -inst -cont Rutoken
Error
+ for LINE in '`cat file`'
+ /opt/cprocsp/bin/amd64/certmgr -inst -cont S
Error
+ for LINE in '`cat file`'
+ /opt/cprocsp/bin/amd64/certmgr -inst -cont 00
Error
+ for LINE in '`cat /home/user/Aktiv`'
+ /opt/cprocsp/bin/amd64/certmgr -inst -cont '00\USER1@R69-20180109'\'''
+ for LINE in '`cat file`'
+ /opt/cprocsp/bin/amd64/certmgr -inst -cont ''\''\\.\Aktiv'
Error
+ for LINE in '`cat file`'
+ /opt/cprocsp/bin/amd64/certmgr -inst -cont Co.
Error
+ for LINE in '`cat file`'
+ /opt/cprocsp/bin/amd64/certmgr -inst -cont Rutoken
Error
+ for LINE in '`cat file`'
+ /opt/cprocsp/bin/amd64/certmgr -inst -cont S
Error
+ for LINE in '`cat file`'
+ /opt/cprocsp/bin/amd64/certmgr -inst -cont 00
Error
+ for LINE in '`cat /home/user/Aktiv`'
+ /opt/cprocsp/bin/amd64/certmgr -inst -cont '01\USER2@R69-20180109'\'''
IN THE IDEAL MUST BE:
/opt/cprocsp/bin/amd64/certmgr -inst -cont '\\.\Aktiv Co. Rutoken S 00 00\USER1@R69-20180109'
/opt/cprocsp/bin/amd64/certmgr -inst -cont '\\.\Aktiv Co. Rutoken S 00 01\USER2@R69-20180109'
I think it's all from special content (file).
Any ideas?
|
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 quoting of $line. See "Understanding "IFS= read -r line"".
I originally included a version using xargs, but I noticed that this did not preserve the backslashes in the file data under some circumstances, and stripped away the single quotes.
| 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 pushd "$dir"; then
wp plugin update --all --allow-root
wp core update --allow-root
wp language core update --allow-root
wp theme update --all --allow-root
rse
popd
fi
done
EOF
What I'd like to ask is actually comprised of these questions:
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 represents each directory inside /var/www/html?
How does the pushd-popd sequence(?) works here? I understand it to "if you are inside $dir which resembles each iteration of the for loop, do stuff".
|
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 includes all files within dir, not just all directories: in a POSIX environment, directories are a file type, but in this case only directories are relevant to the for loop and the subsequent pushd-popd pair.
How does the pushd-popd sequence(?) works here? I understand it to "if you are inside $dir which resembles each iteration of the for loop, do stuff".
pushd and popd are a pair of tools that work with a data structure known as a "stack". Picture a spring-loaded dispenser, like a Pez dispenser.
If you push an item onto a stack, you are storing it for later use, like pushing one 'pill' into the top of the Pez dispenser.
If you pop an item from a stack, you are taking it out for use or reference. This removes it from the stack.
Take a look at this behavior for a simple example of how pushd and popd work:
$ pwd
/home/myuser
$ pushd /etc
/etc ~
$ pwd
/etc
$ pushd /usr/local
/usr/local /etc ~
$ pwd
/usr/local
$ popd
/etc ~
$ pwd
/etc
$ popd
~
$ pwd
/home/myuser
Your for loop basically works by saying if I can push this directory onto the directory stack, then that means firstly that the directory now exists, and secondly that that directory is now the current working directory. It will proceed to do the work, and then popd to go back to wherever it had been before, and then run the next iteration of the loop.
| 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}`" - )"/g' *
done
that I could think of but nothing seemed to work. I ended up just doing it manually since I was only concerned with 1-9 in this case, so
rename 's/- 1 -/- 01 -/g' *
rename 's/- 2 -/- 02 -/g' *
...
Can someone point out why the above didn't work for future reference?
|
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 you asked Perl to interpolate the $( variable which you can read about via perldoc -v '$('. Suffice to say, this regular expression will probably not match your files. (And demonstrates one of the several pitfalls of attempting to embed multiple languages into one gloriously complicated string; there is really no need as Perl can do it all.)
A better approach would be to match and adjust what you are interested in, which here appears to be a number enclosed by hypens; assuming there is only one number in the filename simply match on that saving a backreference ([0-9]+) and use the Perl sprintf function to pad those numbers as appropriate (plus the important /e flag to treat the right hand side as an expression so sprintf actually gets called).
% touch "blah - "{1..9}" - blah"
% ls
blah - 1 - blah blah - 3 - blah blah - 5 - blah blah - 7 - blah blah - 9 - blah
blah - 2 - blah blah - 4 - blah blah - 6 - blah blah - 8 - blah
% rename 's/([0-9]+)/sprintf "%02d", $1/e' *
% ls
blah - 01 - blah blah - 04 - blah blah - 07 - blah
blah - 02 - blah blah - 05 - blah blah - 08 - blah
blah - 03 - blah blah - 06 - blah blah - 09 - blah
%
If there are numbers elsewhere in the filename, then make the regular expression account for that, perhaps something like
% rename 's/- ([0-9]+) -/sprintf "- %d -", $1/e' *
% ls
blah - 1 - blah blah - 3 - blah blah - 5 - blah blah - 7 - blah blah - 9 - blah
blah - 2 - blah blah - 4 - blah blah - 6 - blah blah - 8 - blah
%
To use regular expressions in rename most effectively, see
http://perl-begin.org/topics/regular-expressions/
http://perldoc.perl.org/perlrequick.html
http://perldoc.perl.org/perlretut.html
| 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 channels;
# example filename P209C1T720-T730.csv
lastFile="$dir'P'$id'C'$channel'T1790-T1800.csv'"
# show warning if last file does not exist
if [[ -f $lastFile ]]; then
echo "Last file "$lastFile" is missing"
exit 1
fi
filenameTarget="$targetDir'P'$id'C'$channel'.csv'"
cat $dir'P'$id'C'$channel'T'*'.csv' > $filenameTarget
done;
done
Error
makeCSV.sh: line 12: syntax error near unexpected token `lastFile="$dir'P'$id'C'$channel'T1790-T1800.csv'"'
makeCSV.sh: line 12: ` lastFile="$dir'P'$id'C'$channel'T1790-T1800.csv'"'
OS: Debian 8.5
Linux kernel: 4.6 backports
|
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
if [[ -f $lastFile ]]; then
echo "Last file "$lastFile" is missing"
exit 1
fi
filenameTarget="$targetDir'P'$id'C'$channel'.csv'"
cat $dir'P'$id'C'$channel'T'*'.csv' > $filenameTarget
done;
done
Based on the discussion in the comments I see your confusion with the syntax of the for loop.
This is the rough syntax of the for loop:
for name in list; do commands; done
There always must be a do before commands and a ; (or newline) followed by done after the commands.
Here is a variation with more newlines:
for name in list
do
commands
done
| 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 expected result would be checking the $VAR1, $VAR2, and $VAR3 variables, then print that it's a word.
The current output is:
VAA variable is a word
VAB variable is a word
VAC variable is a word
It's not correct, because the "$VAA" is contains a number.
How can I use variables from outside of for loop?
|
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
if [[ "${varCheck[$var]}" =~ ^[A-Za-z]*$ ]]; then
echo "${var} variable is a word"
else
echo "${var} variable is not a word"
fi
done
Output:
VAB variable is not a word
VAC variable is not a word
VAA variable is a word
| 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 parameters, assume filenames"?
And... if ls output is bad inside of for, what is for doing to get a usable list of filenames that it wont choke on?
|
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 performed on the command line after it has been split
into words. There are seven kinds of expansion performed: brace
expansion, tilde expansion, parameter and variable expansion, command
substitution, arithmetic expansion, word splitting, and pathname
expansion.
...
Pathname Expansion
After word splitting, unless the -f option has been set, bash scans each word for the characters *, ?, and [. If one of these
characters appears, then the word is regarded as a pattern, and replaced with an alphabetically sorted list of filenames matching the pattern (see
Pattern Matching below). If no matching filenames are found, and the shell option nullglob is not enabled, the word is left unchanged.
| 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 the script should exit saying the same.
Next I want to loop based on the array and run a "call" script.
The call script uses the file pattern to check the file count as well.
Below code from call script.
NASFilecnt=`find . -type f -name "${CV_REF_DATA}*.txt" | wc -l`
So, how can run the loop based on the above. Please let me know if there are any queries.
|
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 below should provide a bit of support for your programming effort.
This answer will be similar to my response to your previous question in that we will loop over a set of static strings to test whether filenames containing those strings exists or not.
You may loop over the filename prefixes, and in each iteration, check whether any file with that prefix (and with the .txt filename suffix) exists.
for prefix in CV_REF_DATA_ DB_ONLINE_CL_ DFR_CL_INS_; do
set -- /NAS/CFG/"$prefix"*.txt
if [ -e "$1" ]; then
printf 'There exists names matching "%s"*.txt:\n' "$prefix"
printf '\t%s\n' "$@"
else
printf 'No names matches "%s"*.txt\n' "$prefix"
fi
done
The loop iterates over the filename prefixes, and in each iteration, we try to expand the pattern that should match the files we are interested in for that prefix. The set command will store the matching filenames in the list of positional parameters ("$@"; "$1" is the first element of that list).
In the bash shell, we may write the above block of code as follows.
shopt -s nullglob
for prefix in CV_REF_DATA_ DB_ONLINE_CL_ DFR_CL_INS_; do
names=( /NAS/CFG/"$prefix"*.txt )
if [ "${#names[@]}" -gt 0 ]; then
printf 'There exists names matching "%s"*.txt:\n' "$prefix"
printf '\t%s\n' "${names[@]}"
else
printf 'No names matches "%s"*.txt\n' "$prefix"
fi
done
The nullglob shell option makes non-matching globbing patterns disappear rather than remain unexpanded. We use a named array, names, to hold any matching filenames in each iteration.
For a literal interpretation of your issue: Call some other script if at least one of the tree filenames CV_REF_DATA_09012021.txt,
DB_ONLINE_CL_09012021.txt,
DFR_CL_INS_09012021.txt exists in the directory /NAS/CFG. Add the existing names to an array.
shopt -s nullglob
unset -v names
for name in CV_REF_DATA_09012021.txt DB_ONLINE_CL_09012021.txt DFR_CL_INS_09012021.txt
do
[ -e /NAS/CFG/"$name" ] && names+=( "$name" )
done
if [ "${#names[@]}" -eq 0 ]; then
echo 'no files could be found' >&2
exit 1
fi
# At least one name is in the "names" array.
# Call your other script below here.
| 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)) / $cols ))
for x in $(seq 1 1 $rows)
do
for y in $(seq 1 1 $cols)
do
echo -ne "$count\t"
(( count++ ))
done
echo ""
done
For example, if I enter 6 columns with 28 items this is what the output should look like.
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28
However, this is the output I get with the current code.
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
Thanks in advance for everyone's help!
|
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 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28
This prints each digit read from seq as a left-justified decimal number, allowing four characters of width for each, with no trailing newline. And it then outputs a newline after whenever a row of numbers have been printed, and at the very end.
Using the rs tool:
$ num=28
$ cols=6
$ seq "$num" | rs 0 "$cols"
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28
If you need to do this using a shell loop in e.g. bash:
$ num=28
$ cols=6
$ for ((i=1; i<=num; ++i)); do printf '%-4d' "$i"; (( i%cols == 0 )) && echo; done; echo
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28
This mimics the awk code at the start.
| 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 as many as I would be able to put in?
but when i try and add more numbers
1 2 3 4
nothing happens, it just says at
5
I need to be able to allow for it to loop through an unlimited amount of integers
|
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 variable and a sum of the values
sum=0
for lp in $@
do
sum=$(( sum + lp ))
done
echo $sum
| 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 of my variables.
read NaMeoFFiLe
read startepsilonvalue
NaMeDiR="${startepsilonvalue}plus10steps"
mkdir "${NaMeDiR}"
for ((i=$stteps; i<=$lsteps; i+=1)); do
k=$(bc <<<"""scale=1; $i /10")
echo $k
mkdir "${NaMeDiR}/${k}"
ls "${NaMeDiR}"
sed -e '0,/epsilon = ./{//c\epsilon = '"$startepsilonvalue" -e '}' \
"${NaMeoFFiLe}" > "${k}_${NaMeiFFiLe}"
cat "${NaMeDiR}/${k}/${k}_${NaMeoFFiLe}" &
done
The thing is that I can create the first directory, outside the for loop, but then inside the for loop it only creates the first and last directory and it won't do the changes of the sed command.
The error that I get is that the file does not exist in the directory that I look for which is obvious because the directory hasn't been created.
Is there anything that I am missing?
|
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
Second, you are creating the ${k}_${NaMeiFFiLe} on the parent directory, NOT in the new directories that you are creating. Again, since $k starts with a dot in many cases, it may be hidden on the parent directory. Given the flow of your code, I think you meant to save the file within the new sub-directories. If true, that would look something like this (I replaced the regex with ... for simplification):
sed -e '...' "${NaMeoFFiLe}" > "${NaMeDiR}/${k}/${k}_${NaMeoFFiLe}"
And just as a side note, the mkdir has an option flag -p that can create full directory hierarchies including sub-directories, which means that you wouldn't need an outer loop mkdir:
mkdir -p "${NaMeDiR}/${k}"
Finally, as a more subjective side note, I'd suggest rethinking how you are capitalizing your variable names, because it's incredibly difficult to read for code reviewers... I think some of the other commenters already found some potential typos that could have been avoided with a better naming convention
| 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 - 350ms execs. I'm using an array to maintain PID# but also unsetting the key to reduce the table size, but I have a feeling that, that's the culprit.
#!/bin/bash
threads=()
threadcounter=0
crd=0;
while true;
do
threadcounter=${#threads[@]}
crdcounter=${#crds[@]}
if [ "$threadcounter" -lt 300 ]
then
s1=$(($(date +%s%N)/1000000))
pidf=$(/opt/remi/php/root/usr/bin/php cli.php initformula $crd >> /tmp/logger) &
pidfid=$!
s2=$(($(date +%s%N)/1000000))
echo "Init " $crd $(expr $s2 - $s1 ) "ms"
threads[$pidfid]+=$pidfid
else
for pid in "${!threads[@]}"; do
if [ ! -d "/proc/${pid}" ]
then
unset threads[$pid]
fi
done;
fi;
if [ "$crd" -gt 9999999 ]
then
echo "completed all";
exit;
fi;
crd=$(expr $crd + 1)
done;
|
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 processes.
Otherwise you loop over approximately 300 processes getting the
kernel to populate the /proc virtual filesystem, and testing if a
directory exists. Any missing directories will cause entries to be
deleted from the threads array.
You have a unused array called crds.
Because after the initial 300, each loop of the crd variable will create 1 new copy of cli.php if there are free slots in the process table, but can remove up to 300 if the table is full, at the end of the run we only knew that between 300 and about 9,967,000 cli.php processes have been started, with the number being determined by how fast your machine is, how long cli.php takes to execute and the load on the machine. 6 orders of magnatude is a lot to have to optimize over!
A rule of thumb is that on a modern machine starting 1 process takes 1ms on one core, so you are not doing badly at your initial launch rate. I would expect a significant kink in the launch rate once you run out of free cores to launch new processes.
Improvements
One way to speed this up would be to use ! kill -0 $pid rather than [ ! -d "/proc/${pid}" ] - kill -0 doesn't kill anything but gives an error return if the process doesn't exist. kill is a shell builtin (as is [) but the amount of work the kernel has to do is smaller. This will be most effective if most of time there are no free slots in the threads array.
A second improvement would replace the call to the external program expr with using the builtin $(( ... )) arithmetic, so reducing the overhead of launching a copy of cli.php. This is most effective if most of the time there are free slots in the labels array.
To do much more analysis we need to know the approximate time that cli.php takes to run, and how many runs there are.
As the BUGS section in the bash manual says It's too big and too slow. so it is certainly possible that there is scope for improving the array implementation in bash.
Alternative Implementations
make
In the comments it is suggested to use xargs or parallel. I frequently prefer using make. The first thing to determine how many copies of cli.php are wanted. Then a simple Makefile such as
%:
\t/opt/remi/php/root/usr/bin/php cli.php initformula $@
where \t is a tab character. (This simple version assumes you don't have any files with numeric names in the 0 to 9999999 range). Then invoke make as
make -O -j 300 $(seq 0 9999999) > /tmp/logger
if you want the full 10,000,000 cli.php invocations. Reasons why I prefer make to xargs include not needing to take excessive steps to abort the processing if cli.php returns errors.
xargs
For an xargs solution try
seq 0 9999999 | xargs -n 1 -P 300 /opt/remi/php/root/usr/bin/php cli.php initformula > /tmp/logger
which is simpler.
Bash
However a Bash solution which uses wait -nf and doesn't worry about tracking the PIDs at all might be more to the taste of the OP. It starts the initial 300 processes, then as it detects one of them finishing it will launch another. Once the 10,000,000th has been started it does a final wait to let all the jobs finish. Not exactly the same algorithm but very close.
#!/bin/bash
for(crd=0;crd<300;crd++); do
/opt/remi/php/root/usr/bin/php cli.php initformula $crd &
done > /tmp/logger
for(;crd<=9999999;crd++); do
wait -fn
/opt/remi/php/root/usr/bin/php cli.php initformula $crd &
done >> /tmp/logger
wait
| 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 entries as in
for ((i=0; i<n; i++))
do
file="${filarray[$i]}"
<whatever operation on the file>
done
where the number of entries can be retrieved via
n="${#filearray[@]}"
Note however that this only works if your file-names don't contain special characters (in particular space) and hence, once again, parsing the output of ls or find is not recommended. In your case, I would recommend seeing if the -exec option of find can do what you need to accomplish.
| 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 moved/renamed with its leading number increased by 2, so the list would look like this:
01_file_name.log
01_file_name.txt
02_file_name.log
02_file_name.txt
05_file_name.log
05_file_name.txt
06_file_name.log
06_file_name.txt
07_file_name.log
07_file_name.txt
I'm thinking of something like:
bash script.sh 03 02 while 03 on $1 is the number of the file name to start with and 02 on $2 the number to be added. I tried to achieve this with a nested for-loop but I had to give up on the combination of using a counter ((++)) to make the loop run only through the files from the given number on wards.
|
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
PREFIX=${filename%%_*}
NEWPREFIX=$(expr $PREFIX + $SHIFT)
if [ $PREFIX -ge $BOTTOM ]; then
NEWPREFIX=$(printf %${MAXDIGITS}d $NEWPREFIX)
mv $filename ${NEWPREFIX}_${filename#*_}
fi
done
To use it:
./myscript <BOTTOM> <SHIFT> <MAXDIGITS>
### Example:
./miscript 03 02 2 #This means "Start at 03_filename.*, shift the prefixes by 2 and use 2 digits to construct the new prefixes".
If you have other files in the same directory that don't conform to the same syntax (prefix_filename.{txt,log}) you have to filter them.
Also, I used the "_" to separate prefix from filename, so if you change that you'll need to fix the code.
| 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 validate my HTML.
I want, that HTMLTidy validate all HTML in folder output and subfolders of this folder.
See simply configuration of my project.
Working equivalent Windows batch script:
@echo off
FOR /R %%i IN (*.html) DO echo %%i & tidy -mq %%i
3. Steps to reproduce
I print in console:
cd output && bash ../tidy.sh
../tidy.sh — path to my script, see simply configuration.
4. exit code 0
If tidy.sh:
shopt -s globstar
for i in **/*.html; do
tidy -mq $i
echo $i
done
Travis CI build passed:
$ cd output && bash ../tidy.sh
line 8 column 9 - Warning: trimming empty <span>
SashaInFolder.html
line 8 column 9 - Warning: trimming empty <div>
subfolder/SashaInSubFolder.html
The command "cd output && bash ../tidy.sh" exited with 0.
Done. Your build exited with 0.
5. exit code 1
Elif:
shopt -s globstar
for i in **/*.html; do
echo $i
tidy -mq $i
done
Travis CI build failed:
$ cd output && bash ../tidy.sh
SashaInFolder.html
line 8 column 9 - Warning: trimming empty <span>
subfolder/SashaInSubFolder.html
line 8 column 9 - Warning: trimming empty <div>
The command "cd output && bash ../tidy.sh" exited with 1.
Done. Your build exited with 1.
6. Not helped
I try printf instead of echo → I get same behavior.
I can't find answer to my question in Google.
|
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 return false/failure if any of the tidy command fails, you'd need to either record the failure, or exit upon the first failure:
#! /bin/bash -
shopt -s globstar
ok=true
for i in ./**/*.html; do
if tidy -mq "$i"; then
printf '%s\n' "$i"
else
ok=false
fi
done
"$ok"
or:
#! /bin/bash -
shopt -s globstar
for i in ./**/*.html; do
tidy -mq "$i" || exit # if tidy fails
printf '%s\n' "$i"
done
That one could still return false/failure if printf fails (for instance, when stdout is to a file on a filesystem that is full).
If you want to ignore any error and your script to return true/success in any case, just add a true or exit 0 at the end of your script.
¹ at least for the body part. For for i in $(exit 42); do :; done, most shells return 0 (AT&T ksh being the exception). They all return 0 for for i in; do :; done < "$(echo /dev/null; exit 42)".
| 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 block, or if the version is 10 or 9, it should execute a block.
12 or 11 has the alert logs under TRACE_FILE's value, 10 or 9 wont have any output for TRACE_FILE, so 10 and 9 should clear the alert log based on BDUMPs value.
So I have drafted the below script and it works fine, I feel the script has got lot of repetition where i applied logic for DB_VERSION.
Any ideas on how could this script be enhanced
#############################################################################################################################################################
#!/bin/bash
#############################################################################################################################################################
TODAY=`date +%Y-%m-%d`
DATE=`date +%Y%b%d`
YESTERDAY=`date -d '-1 day' +%b%Y`
YDAY=`date -d '-1 day' +%Y%b%d`
HOST=`hostname`
LOG_LOCATION="/home/oracle/utility_script/dba_maint/logs"
mkdir -p ${LOG_LOCATION}
LOG_FILE="${LOG_LOCATION}/oracle_files_cleanup_${DATE}.log"
rm ${LOG_FILE} 2>/dev/null
dbenv ()
{
ORACLE_HOME=`cat /etc/oratab | grep ^$ORACLE_SID | cut -d":" -f2`; export ORACLE_HOME
PATH=$ORACLE_HOME/bin:$PATH ; export PATH
LD_LIBRARY_PATH=$ORACLE_HOME/lib ; export LD_LIBRARY_PATH
DB_VERSION=`cat /etc/oratab | grep "^$ORACLE_SID" | cut -d":" -f2 | rev | cut -d"/" -f2| rev | cut -d"." -f1`; export DB_VERSION
}
dbcheck()
{
sqlplus / as sysdba << EOF &>${LOG_LOCATION}/dbcheck.out
exit
EOF
}
sql_plus()
{
sqlplus -s / as sysdba << EOF &>/dev/null
SET NEWPAGE NONE;
set lines 200 pages 300;
set feedback off;
set heading off;
spool ${LOG_LOCATION}/$1.log
$2
exit
EOF
}
for SID in `ps -eaf | grep pmon | grep -v grep | awk '{print $8}' | sort | cut -d"_" -f3`
do
ORACLE_SID=${SID} ; export ORACLE_SID
dbenv ${ORACLE_SID} #-- Passing the ORACLE_SID to dbenv function to source the database.
if [ ${DB_VERSION} -eq 11 -o ${DB_VERSION} -eq 12 ]
then
dbcheck
DB_CHECK=`cat ${LOG_LOCATION}/dbcheck.out | egrep "ORA|SP2|idle"`
LOWER_SID=`echo ${ORACLE_SID} | tr '[A-Z]' '[a-z]'`
#-- Queries to fetch the proper log location from database
ADUMP="select DISPLAY_VALUE from v\$parameter where name='audit_file_dest';"
BDUMP="select DISPLAY_VALUE from v\$parameter where name='background_dump_dest';"
CDUMP="select DISPLAY_VALUE from v\$parameter where name='core_dump_dest';"
UDUMP="select DISPLAY_VALUE from v\$parameter where name='user_dump_dest';"
TRACE_FILE="select DISPLAY_VALUE from v\$parameter where name='diagnostic_dest';"
#-- Calls the sql_plus function with the parameters as the logname and SQL query
sql_plus "adump_${ORACLE_SID}" "${ADUMP}"
sql_plus "bdump_${ORACLE_SID}" "${BDUMP}"
sql_plus "cdump_${ORACLE_SID}" "${CDUMP}"
sql_plus "udump_${ORACLE_SID}" "${UDUMP}"
sql_plus "trace_${ORACLE_SID}" "${TRACE_FILE}"
#-- Remove any empty lines after the log location
ADUMP_LOC=`cat ${LOG_LOCATION}/adump_${ORACLE_SID}.log | sed 's/[[:blank:]]*$//'`
BDUMP_LOC=`cat ${LOG_LOCATION}/bdump_${ORACLE_SID}.log | sed 's/[[:blank:]]*$//'`
CDUMP_LOC=`cat ${LOG_LOCATION}/cdump_${ORACLE_SID}.log | sed 's/[[:blank:]]*$//'`
UDUMP_LOC=`cat ${LOG_LOCATION}/udump_${ORACLE_SID}.log | sed 's/[[:blank:]]*$//'`
TRACE_LOC=`cat ${LOG_LOCATION}/trace_${ORACLE_SID}.log | sed 's/[[:blank:]]*$//'`
#-- If the Database is not in idle state or without any errors, start housekeeping
if [ -z "${DB_CHECK}" ]
then
echo -e "\t\t\t\t HOUSEKEEPING for database : ${ORACLE_SID}" >>${LOG_FILE}
echo -e "\t\t\t\t ============ === ======== = =============" >>${LOG_FILE}
#-- Cleans .aud files older than 60 days in ADUMP location
if [ ! -z "${ADUMP_LOC}" ]
then
echo -e "\t\t\tAdump cleanup" >> ${LOG_FILE}
fi
#-- Cleans .trm or .trc files older than 60 days in BDUMP location
if [ ! -z "${BDUMP_LOC}" ]
then
echo -e "\n\n\t\t\tBdump cleanup" >> ${LOG_FILE}
fi
#-- Cleans .trm or .trc files older than 60 days in CDUMP location
if [ ! -z "${CDUMP_LOC}" ]
then
echo -e "\n\t\t\tCdump cleanup" >> ${LOG_FILE}
fi
#-- Cleans .trm or .trc files older than 60 days in UDUMP location
if [ ! -z "${UDUMP_LOC}" ]
then
echo -e "\n\t\t\tUdump cleanup" >> ${LOG_FILE}
fi
#-- Rotates the Database alert log on 01st of every month.
if [ `date +%d` -eq 01 ]
then
if [ ! -z "${TRACE_LOC}" ]
then
echo -e "\n\t\t\tALERT LOG ROTATION" >> ${LOG_FILE}
fi
fi
#-- Rotates the Listener log on 01st of every month.
if [ `date +%d` -eq 01 ]
if [ ! -z "${TRACE_LOC}" ]
then
echo -e "\n\t\t\tLISTENER LOG ROTATION" >> ${LOG_FILE}
fi
fi
else
echo -e "ERROR : Please fix the below error in database - ${ORACLE_SID} on host - ${HOST} \n ${DB_CHECK}" >> ${LOG_LOCATION}/house_keeping_fail_${ORACLE_SID}_${DATE}.log
fi
elif [ ${DB_VERSION} -eq 10 -o ${DB_VERSION} -eq 9 ]
then
dbcheck
DB_CHECK=`cat ${LOG_LOCATION}/dbcheck.out | egrep "ORA|SP2|idle"`
#-- Queries to fetch the proper log location from database
ADUMP="select DISPLAY_VALUE from v\$parameter where name='audit_file_dest';"
BDUMP="select DISPLAY_VALUE from v\$parameter where name='background_dump_dest';"
CDUMP="select DISPLAY_VALUE from v\$parameter where name='core_dump_dest';"
UDUMP="select DISPLAY_VALUE from v\$parameter where name='user_dump_dest';"
#-- Calls the sql_plus function with the parameters as the logname and SQL query
sql_plus "adump_${ORACLE_SID}" "${ADUMP}"
sql_plus "bdump_${ORACLE_SID}" "${BDUMP}"
sql_plus "cdump_${ORACLE_SID}" "${CDUMP}"
sql_plus "udump_${ORACLE_SID}" "${UDUMP}"
#-- Remove any empty lines after the log location
ADUMP_LOC=`cat ${LOG_LOCATION}/adump_${ORACLE_SID}.log | sed 's/[[:blank:]]*$//'`
BDUMP_LOC=`cat ${LOG_LOCATION}/bdump_${ORACLE_SID}.log | sed 's/[[:blank:]]*$//'`
CDUMP_LOC=`cat ${LOG_LOCATION}/cdump_${ORACLE_SID}.log | sed 's/[[:blank:]]*$//'`
UDUMP_LOC=`cat ${LOG_LOCATION}/udump_${ORACLE_SID}.log | sed 's/[[:blank:]]*$//'`
#-- If the Database is not in idle state or without any errors, start housekeeping
if [ -z "${DB_CHECK}" ]
then
#-- Cleans .aud files older than 60 days in ADUMP location
if [ ! -z "${ADUMP_LOC}" ]
echo -e "\t\t\tAdump cleanup" >> ${LOG_FILE}
fi
#-- Cleans .trm or .trc files older than 60 days in BDUMP location
if [ ! -z "${BDUMP_LOC}" ]
then
echo -e "\n\n\t\t\tBdump cleanup" >> ${LOG_FILE}
fi
#-- Cleans .trm or .trc files older than 60 days in CDUMP location
if [ ! -z "${CDUMP_LOC}" ]
then
echo -e "\n\t\t\tCdump cleanup" >> ${LOG_FILE}
fi
#-- Cleans .trm or .trc files older than 60 days in UDUMP location
if [ ! -z "${UDUMP_LOC}" ]
then
echo -e "\n\t\t\tUdump cleanup" >> ${LOG_FILE}
fi
#-- Rotates the ${DB_VERSION} version Database alert log on 01st of every month.
if [ `date +%d` -eq 01 ]
then
if [ ! -z "${BDUMP_LOC}" ]
then
echo -e "\n\t\t\tALERT LOG ROTATION" >> ${LOG_FILE}
fi
fi
else
echo -e "ERROR : Please fix the below error in database - ${ORACLE_SID} on host - ${HOST} \n ${DB_CHECK}" >> ${LOG_LOCATION}/house_keeping_fail_${ORACLE_SID}_${DATE}.log
fi
fi
done
exit $?
#---------------------------------------------------------------------END-----------------------------------------------------------------------------------#
|
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:
ps -eaf | awk '/pmon/ && ! /grep/ {print $8}'
Similarly, piping grep into cut is usually better done with awk. e.g instead of:
cat /etc/oratab | grep ^$ORACLE_SID | cut -d":" -f2
use
awk -F: "/^$ORACLE_SID/ {print \$2}" /etc/oratab
(normally you wouldn't escape the $ of $2 in an awk script because it's more usual to single-quote the entire awk script. In this case, we're double-quoting the awk script so that we can use the bash variable $ORACLE_SID in awk, so we need to backslash-escape awk's $2 to prevent the shell from replacing it with its own $2)
you don't need to do pipe ps into grep or awk anyway. You can just do ps h -o cmd -C pmon instead. Or use pgrep.
sed can read files by itself, you don't need to pipe catinto sed. So can grep and awk and perl and cut and every other standard text-processing tool.
[ -n "$var" ] is the same as [ ! -z "$var" ].
-z tests for empty string, -n tests for non-empty string.
there are several occasions where you haven't double-quoted your variables. you should (almost) always double-quote variables when you use them.
single-quotes are for fixed, literal strings. double-quotes are for when you want to interpolate a variable or command substitution into a string.
indenting with 8 characters is excessive. use 2 or 4 spaces per indent level. or set the tab stop in your editor to 2 or 4 spaces.
it's a good habit to use lowercase or MixedCase for your own variables, leaving ALLCAPS variable names for standard utilities and common programs.
tools like sqlplus, mysql, psql, etc are very convenient for doing scripted database queries in sh or bash etc but you have to be extremely careful about any variables you use with SQL commands - especially if the values in the variables come from user-supplied data, or other "untrusted" sources. It is very easy to break a script if the input data is unvalidated and unsanitised. It is just as easy to create an SQL injection bug.
For non-trivial SQL queries, you should probably learn perl or python or some other language with a database library that supports placeholders to avoid any issues with quoting of variables in sql commands.
| 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 situation in which I can't install them directly but I need to use a script.
How could I do? This way install the packages in different rows and is not what I need.
for pkg in "$@"
do
yum -y install "$pkg"
done
|
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):
bash ~/myScript.sh arg0 arg1
The for loop, which is based on the undefined variable myVar, would apply arg0 and arg1 to itself (sorry if this phrasing is lousy) and I'll get this output:
Hi
Hi
(one "Hi" per argument).
I originally assumed that one for loop works with one argument so if I would have myVar_0 and myVar_1 with arg0 and arg1, then myVar_0 will work with arg_0 and myVar_1 will work with arg1 but I further tested and I was wrong --- all for loops worked with all arguments:
#!/bin/sh
for myVar_0; do
echo "Hi"
done
for myVar_1; do
echo "Hello"
done
will return in bash myScript arg0 arg1:
Hi
hello
Hi
hello
Sidenote: I assume that if would want "1 argument per 1 for loop" I just need to use a Bash function for local scope.
My question
What is the name of this "all arguments per all for loops" matching that Bash does?
|
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
"header"
"header
2"
as it should.
Is there a way to get around this? It's similar to this post with a list of files with spaces, but I'm not doing files, and I'd like to keep them on one line, as there will be many entries.
|
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 more information.
| 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 files within each "dicom" subfolder. Interestingly, if I specify absolute paths in both places, but with the wildcard * intact to include all folders within the parent directory, the loop runs only once as desired. How can I get the loop to run only once using relative paths?
|
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 second subfolder and does the same
Try this:
for d in ./*/ ; do (cd "$d" && dcm2nii -n y -r y -x y -g n dicom/); done;
or (possibly) this:
dcm2nii -n y -r y -x y -g n ../*/dicom/
| 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.txt
"
done
/dir/xyx_blue0/details.txt
/dir/xyz_blue1/details.txt
/dir/xyx_green2/details.txt
/dir/xyz_green4/details.txt
/dir/xyx_red1/details.txt
/dir/xyz_red8/details.txt
But I actually need to loop through the output of ls so I can do things to the files, however the variable doesn't expand:
for i in ${servers[@]}; do
ssh $i "
for i in $(ls /dir/xyz_${i}*/details.txt); do
echo $i
done
"
done
not found: /dir/xyx_blue*/details.txt
not found: /dir/xyx_green*/details.txt
not found: /dir/xyx_red*/details.txt
How can I get $i to expand when running a loop on the remote host?
|
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 to do instead)?).
Instead:
servers=(
blue
green
red
)
for server in "${servers[@]}"; do
ssh -T "$server" <<END_SCRIPT
shopt -s nullglob
for pathname in /dir/xyz_$server*/details.txt; do
printf 'file path is "%s"\n' "\$pathname"
done
END_SCRIPT
done
This uses an unquoted "here-document" as the script that is sent to the remote servers. The script first sets the nullglob shell option (this is assuming that the remote shell is bash) to avoid looping at all in the inner loop if the pattern does not match any filenames. It then iterates over the pattern /dir/xyz_$server*/details.txt where $server will be substituted with the current server name.
The loop then prints out a short message about what filenames matched the pattern, and the code ensures that the $pathname variable is not expanded by the local shell by escaping the $.
Note that $ in $server is unescaped and will therefore be expanded by the local shell, which is what we want, but that $ in $pathname needs to be escaped to supress the local expansion.
We don't need to set IFS to anything non-default. I'm assuming you did that to be able to write the array assignment as you did, or for some other reason, but none of the code above needs that.
I'm using -T with ssh to explicitly turn off pseudo-TTY allocation.
You could also provide the script as a single string if you feel that this is somehow needed:
servers=(
blue
green
red
)
for server in "${servers[@]}"; do
ssh "$server" "
shopt -s nullglob
for pathname in /dir/xyz_$server*/details.txt; do
printf 'file path is \"%s\"\n' \"\$pathname\"
done"
done
In this case, you must additionally ensure that each embedded double quote is escaped (or they would end the double-quoted string that constitutes the remote shell script).
| 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 read line by line. So each line has 2 args (separated by a space) to be passed: input-file and output-file.
Example of file with arguments (call it File-With-Multiple-Arguments-Per-Line.txt):
input-file-1-path/input-file-1-name.sql output-file-1-path/output-file-1-name.sql
input-file-2-path/input-file-2-name.sql output-file-2-path/output-file-2-name.sql
input-file-3-path/input-file-3-name.sql output-file-3-path/output-file-3-name.sql
input-file-4-path/input-file-4-name.sql output-file-4-path/output-file-4-name.sql
I tried this:
for arg in $(< /Users/Repository/File-With-Multiple-Arguments-Per-Line.txt);
do python /Users/Git-Repos/MyProgram.py "$arg" "$arg" ;
done.
Usage is such: python MyProgram.py input-file.txt output-file.txt
I does what need. Though for some reason it processes each argument 3 times (so, 1st arg is input-file is also treated both as output-file; same with 2nd arg). So I end up modifying the input file, which I should not.
I know this as both Input and Output files are 2 separate git Repositories.
I've also used only one "$arg" but then I'm seeing that my program does not receive a required 2nd argument (output-file). Instead of my output-file I see output: <stdout>
But using "$arg" "$arg" leads to incorrect interpretation of my program. As if does the same task 3 times - first time does what is intended; second time using input-file as output and input; third time using output-file as output and input.
I've tried the solution below as well, but then my program does not do anything. Though it displays the output in my terminal as if it did what was supposed to be done. And no error appears.
For reference: Reading multiple arguments for a shell script from file
while read x y; do
python /Users/Git-Repos/MyProgram.py "$x" "$y"
done < /Users/Repository/File-With-Multiple-Arguments-Per-Line.txt
|
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 arbitrary file paths¹ including ones with whitespace or even newline characters. Note however that the quoting syntax is different from that of modern sh². Both '...' and "..." are strong quotes and cannot contain newline characters. For instance you could have:
tamed-input-file tamed-output-file
"Input: it's "'such a "cool" path' 'Output: Not as cool'\
'as one with'\
'newline characters'
$ xargs -L1 <a printf '1:<%s> 2:<%s>\n'
1:<tamed-input-file> 2:<tamed-output-file>
1:<Input: it's such a "cool" path> 2:<Output: Not as cool
as one with
newline characters>
Note that depending on the xargs implementations, pythons stdin will be either opened read-only on /dev/null or shared with that of xargs (so be coming from File-With-Multiple-Arguments-Per-Line.txt as well), so it's important that python doesn't read from its stdin. With the GNU implementation of xargs, you can use:
xargs -L1 -a File-With-Multiple-Arguments-Per-Line.txt python MyProgram.py
to work around it.
Also note that with most implementations of xargs, if File-With-Multiple-Arguments-Per-Line.txt is empty, the command is still run once without arguments. With a few xargs implementations, that can be avoided with the -r option.
About your:
for arg in $(< /Users/Repository/File-With-Multiple-Arguments-Per-Line.txt);
do python /Users/Git-Repos/MyProgram.py "$arg" "$arg" ;
done
First note that except in zsh, that unquoted $(<...) is subject to globbing in addition to IFS-splitting, so you'd need a set -o noglob beforehand to avoid problems with filenames containing wildcard character.
Then, in each pass of the loop, you're getting one IFS-delimited ($IFS containing space, tab and newline (and NUL in zsh) by default) and passing that same word twice to python. To get two words at a time, you'd need zsh and:
for file1 file2 in $(<File-With-Multiple-Arguments-Per-Line.txt); do
python MyProgram.py $file1 $file2
done
Or in bash:
set -o noglob
set -- $(<File-With-Multiple-Arguments-Per-Line.txt)
while (( $# > 0 )); do
python MyProgram.py $1 $2
shift "$(( $# < 2 ? $# : 2 ))"
done
That means the file paths can't contain space, tab nor newline characters though.
To do something similar to xargs -L1 and pass all the $IFS-delimited word from each line, in zsh:
while IFS= read -ru3 line; do
python MyProgram.py $=line 3<&- # $=line for explicit IFS-splitting
done 3< File-With-Multiple-Arguments-Per-Line.txt
Or:
while read -ru3 -A files; do
python MyProgram.py $files 3<&-
done 3< File-With-Multiple-Arguments-Per-Line.txt
(would also work in ksh93 and bash except you need "${files[@]}" instead of $files there (also works in zsh), and -a instead of -A in bash).
POSIXly:
set -o noglob
while IFS= read -r <&3 line; do
python MyProgram.py $line 3<&- # implicit split+glob with glob disabled above
done 3< File-With-Multiple-Arguments-Per-Line.txt
That still doesn't allow arbitrary file paths. For a splitting of lines into words that understand some form of quoting like xargs -L1 does, with zsh:
while IFS= read -ru3 line; do
python MyProgram.py "${(Q@)${(z)line}}" 3<&- # $=line for explicit IFS-splitting
done 3< File-With-Multiple-Arguments-Per-Line.txt
Where the z parameter expansion flag does the same tokenisation as in the zsh language, Q removes one layer of quoting, and @ within quotes preserves empty arguments (like "$@" does).
Then you can use:
"Input: it's "'such a "cool" path' $'Output: Not as cool\nas one with\nnewline characters'
¹ as long as they're not too long and with some xargs implementations, that they can be decoded as valid text in the user's locale.
² It's closer to that of the Mashey shell (aka PWB shell, xargs being introduced in PWB Unix in the late 70s).
| 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 directory"
continue
fi
echo "$f"
fi
done
I want to skip TEST directory.
|
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"
continue
fi
# Code ...
fi
done
| 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/wikipedia_en_all_mini_2022-09.zim
ports:
- 8080:80
command:
/data/wikipedia_en_all_mini_2022-09.zim
/data/gutenberg_en_all_2022-10.zim
I'm attempting to create a script that will search for all .zim files in /home/meijin3/zim/. It will replace any existing lines in my compose file that contain references to .zim files.
#!/bin/bash
yaml=example.yaml
sed -i '/.zim/d' $yaml
for i in "$(find /home/meijin3/zim/*.zim -printf '%f\n')"; do \
line1='home/emilio/zim/'"$i"':/data/'"$i"
sed -i -e "\,kiwix_data,a "'\ \ \ \ \ \ - '"$line1" "$yaml"; done
batcat $yaml
For some reason that I can't seem to understand I keep getting the following error:
sed: couldn't open file ikipedia_en_all_mini_2022-09.zim:/data/gutenberg_en_all_2022-10.zim: No such file or directory
If I have only one file in /home/meijin3/zim/, my script runs without any issues (other than the fact that I have yet to add the lines to the command section yet).
Am I not using the proper syntax for the sed command? Perhaps the issue lies somewhere else. If you're able to help, it is much appreciated!
|
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 -e "\,command:,a "'\ \ \ \ \ \ /data/'"$i" "$yaml"
done
| 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 $search_filename; do
echo $files
done
I had expected to get a list of the files fitting to the search criterium in the last echo. Instead I get the search criterium itself.
For testing I tried F="*.txt";for files in $F;do echo $files;done directly in the bash (which worked and I got a list of files) and in the same script (which got me the output *.txt
Already tried different variable expansion stuff (e.g. $(..) ((..)) ${..}, which all did not work.)
Why is that and how can I get around?
Would be great to find help.
Best wishes
Caro
using Ubuntu 22.04LTS, KDE/plasma desktop; bash v5.1.16(1). Terminal: konsole v21.12.3
|
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.
If your script is run from different directories, your globs will expand differently (unless, of course, the same filenames exist in each of those directories).
For example:
user@host:~ 0 $ touch {a,b,c}.log
user@host:~ 0 $ ls -l
total 0
-rw------- 1 user staff 0 Jul 25 10:27 a.log
-rw------- 1 user staff 0 Jul 25 10:27 b.log
-rw------- 1 user staff 0 Jul 25 10:27 c.log
user@host:~ 0 $ shopt nullglob
nullglob off
user@host:~ 1 $ echo *.log
a.log b.log c.log
user@host:~ 0 $ echo *.bak
*.bak
user@host:~ 0 $ shopt -s nullglob
user@host:~ 0 $ shopt nullglob
nullglob on
user@host:~ 0 $ echo *.log
a.log b.log c.log
user@host:~ 0 $ echo *.bak
user@host:~ 0 $
On an unrelated note... Perhaps consider habitualizing intentional quoting, at least whenever appropriate; e.g., echo "$files", as opposed to echo $files to improve command-line safety and whitespace handling.
If interested, use of arrays may also be desirable; e.g.,
#!/bin/bash -e
export PATH=/bin:/sbin:/usr/bin:/usr/sbin
shopt -s nullglob
declare -a files=()
case "$1" in
'logs')
files=(*.log)
;;
'baks')
files=(*.bak)
;;
*)
echo 'invalid argument' 1>&2
exit 1
;;
esac
for f in "${files[@]}"; do
echo "$f"
done
| 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 15000.
how can I write the code? thank you
|
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 i in {0..9}; do
curl "$target" >/dev/null &
done
wait
j=$(( j + 1 ))
done
Or you could count the total number of times you call curl, which would allow you to change the number of times you run curl in the inner loop without having to adjust the outer loop at all and still retain the same number of total calls:
target=${1:-http://web1.com}
n=15000
while [ "$n" -gt 0 ]; do
for i in {0..9}; do
curl "$target" >/dev/null &
n=$(( n - 1 ))
done
wait
done
The test [ "$n" -gt 0 ] is true for as long as n is strict greater than zero.
Or, to avoid decreasing n inside the inner loop:
target=${1:-http://web1.com}
n=15000
while [ "$n" -gt 0 ]; do
for i in {0..9}; do
curl "$target" >/dev/null &
done
n=$(( n - 10 ))
wait
done
Or, you have a xargs utility that can run things in parallel with -P, and you want to keep 10 curl processes running constantly:
target=${1:-http://web1.com}
n=15000
yes | head -n "$n" | xargs -I {} -P 10 curl "$target" >/dev/null
This creates 15000 lines using yes and head and feeds them into a xargs command that will keep 10 curl processes running at any time until all lines have been exhausted (one curl process will be spawned for each line read from head). The actual contents of the lines generated by yes will be the single character y, but these are thrown away and not used at all.
| 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 "$d" "[email protected]"; done
But how do i do the reverse? [email protected] ==> name1
|
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 d in ./*@domain.com/; do mv "$d" "${d%@*}"; done
| 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.ipynb
as you can see, I have file names with spaces. How can I loop thought all the subdirectories in Fixed_Zip folder, and perform the command:
jupytext --to py {file} ?
One more thing, I'm doing the command from groovy file, so I guess there are some syntax to adjust.
I was able to run the below in my private env and it's working:
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for i in `find . -name '*.ipynb' -type f`; do
jupytext --to py "$i"
done
IFS=$SAVEIFS
However, when I did the same in the groovy file:
sh '''
SAVEIFS=$IFS
IFS=$(echo -en "\\n\\b")
for i in `find . -name '*.ipynb' -type f`; do
jupytext --to py "$i"
done
IFS=$SAVEIFS
'''
I got the below error:
raise InconsistentPath(
jupytext.paired_paths.InconsistentPath: './ipytho' is not a notebook.
|
"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 reverse read ("R1" is reverse, "R2" is forward).
I want to concatenate the files from the 4 different lanes for each sample and this for the forward read (R1) and the reverse read (R2) separately.
So for this specific sample that would be:
For the forward reads:
cat GC082_F4.lane1.1901.R1.fastq.gz \
GC082_F4.lane2.1901.R1.fastq.gz GC082_F4.lane3.1901.R1.fastq.gz \
GC082_F4.lane4.1901.R1.fastq.gz > GC082_F4.R1.fastq.gz
For the reverse reads:
cat GC082_F4.lane1.1901.R2.fastq.gz \
GC082_F4.lane2.1901.R2.fastq.gz GC082_F4.lane3.1901.R2.fastq.gz \
GC082_F4.lane4.1901.R2.fastq.gz > GC082_F4.R2.fastq.gz
But since I have to do this for +100 samples, I was wondering whether I could use one single loop for this?
Thank you in advance!
|
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"_R1.fastq.gz
cat "$sample".*.R2.fastq.gz > "$sample"_R2.fastq.gz
done
You can also provide a list of sample names as input:
while read sample; do
cat "$sample".*.R1.fastq.gz > "$sample"_R1.fastq.gz
cat "$sample".*.R2.fastq.gz > "$sample"_R2.fastq.gz
done < sample.names.txt
| 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 move them to path3
I tried the below command from '/data/run' , but it is taking the whole path as file name and throwing error.
$for FILENAME in /data/output/*.txt; do mv $FILENAME /data/archive/archive_$FILENAME; done
How can I do that. Thanks.
|
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 thou shall quote filename always.
| 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
swu_run3_P_076_vol_002.nii
/P_102
/run1
/run2
/run3
swu_run1_P_102_vol_001.nii
swu_run1_P_102_vol_002.nii
swu_run2_P_102_vol_001.nii
swu_run2_P_102_vol_002.nii
swu_run3_P_102_vol_001.nii
swu_run3_P_102_vol_002.nii
I would like to move the three sets of files to its own subfolders (run1, run2 and run3) within the existing subfolder:
/Analysis
/P_076
/run1
swu_run1_P_076_vol_001.nii
swu_run1_P_076_vol_002.nii
/run2
swu_run2_P_076_vol_001.nii
swu_run2_P_076_vol_002.nii
/run3
swu_run3_P_076_vol_001.nii
swu_run3_P_076_vol_002.nii
/P_102
/run1
swu_run1_P_102_vol_001.nii
swu_run1_P_102_vol_002.nii
/run2
swu_run2_P_102_vol_001.nii
swu_run2_P_102_vol_002.nii
/run3
swu_run3_P_102_vol_001.nii
swu_run3_P_102_vol_002.nii
The below code does the trick when I run the script within the subfolder (P_XXX):
for f in swu_run?_*.nii; do
num=${f:7:1}
mv "$f" run"$num"/
done'
But I am struggling to find the appropriate for loop to make it work from the parent directory (Analysis), rather than manually running it within each subfolder. I tried the following:
find . -type f -name '*.nii' -exec bash -c '
for f in swu_run?_*.nii; do
num=${f:7:1}
mv "$f" run"$num"/
done' bash {} +
This returns the error message cannot stat 'swu_run?_*.nii': No such file or directory.
How do I run the code at the level of the Analysis folder, so that each P_XXX subfolder is reorganised in three further subfolders (run1, run2 and run3) with their matching files in one go?
|
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 missing).
The parameter expansion ${f%/*} removes the shortest suffix pattern /* leaving the path of the parent directory.
| 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 current date and time used in the subject line.
#!/bin/bash
# to run type "bash email_live_listing.sh"
dt_now_start=`date +"%Y-%m-%d %T"`
fn_dt_now_start=`date '+%Y_%m_%d__%H_%M_%S'`; #use to generate file name with date
currentdir="$(pwd)" #get current directory
ls $currentdir/us*.pdf -tp | grep -v '/$fn_pdf' #place files into variable
echo "$fn_pdf"
ITER=0
for t in ${fn_pdf[@]}; do
swaks --to [email protected] -s smtp.gmail.com:587 -tls -au [email protected] -ap password --header "Subject: Updated file ${fn_dt_now_start}" --body "Email Text" --attach-type ./${fn_pdf} -S 2
let ITER+=1 #increment number
done
Ps: I'm using Ubuntu and Swaks since it's compact and lightweight, and will be run from a raspberry pi, but I'm willing to try other options.
|
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
attach_files="${attach_files} --attach-type ${t}" #will build list of files to attach
done
swaks --to [email protected] -s smtp.gmail.com:587 -tls -au [email protected] -ap <email_sending_from_password>] --header "Subject: Listings - ${fn_dt_now_start}" --body "Listings Email Text" ${attach_files} -S 2
| 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 # this is the aggregated result for the core
I can see people thinking now: this is obviously the instrumentation within the loop core. But no. I have seen this in a far more complex loop with IO operation, sort, uniq, if, cp... After a few runs, I had between 100x-1000x overhead for the whole loop!!
But, just to be sure, I swapped the echo blabla with date +%s%N. The results:
diffb: 3713962570ns
diffba: 2662492ns
It is definitely NOT the instrumentation!
Ok, then try this:
a=0; while [[ $((a++)) -lt 1000 ]];
results:
diffb: 3761656210ns
diffba: 1953502ns
Am I missing here something? Is there something glaringly obvious here, why these results are false? Or did I just stumbled upon reality? Bash loops have the highest overhead in the universe??
(I wanted to optimize the code, so I started to measure a baseline, but it seems, it is beyond optimization.)
EDIT: I did something else, I dropped the iteration count from 1000 to 500 (I used the while loop for this), results:
diffb: 1886513017ns
diffba: 2328892ns
compare with:
diffb: 3761656210ns
diffba: 1953502ns
It really does seem to be the loop overhead, since the core is already hitting some non-linear timing, maybe some constant initialization, or some kernel caching stuff, whatever.
|
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 mentioned is the number of files that will be created with the columns delimeted by var_i_1 and var_f_1, and so on.
I used the follow script:
n_blocks=$(wc -l "a.temp" | awk '{print $1}') # number of blocks to be created, a.temp is the file with the number of blocks
for i in $(seq 1 1 $n_blocks) # to iterate of first to n_blocks
do
awk -v v_i="$var_i_$i" -v v_f="$var_f_$i" '{ # to declare variables of lower ($var_i_$i) and upper ($var_f_$i) bounds for each iteraction to awk command
for (i=v_i;i<=v_f;i++) {printf (i==1?"":FS)$i}; print "" # for statement to print all comlumns between specified in v_i and v_f variables in each iteraction
}' <a.ped_snps.temp > block_$i.txt # print one txt file with each block for each iteraction
done
This code runs and give the files in correct number of iteractions specified in for command, however, only the first column is printed in the output of each file.
When a I used only the awk (as below) with var_i_1 and var_f_1 bash variables (with vaules 2 and 4, respectively, previously stored) the output (block_1.txt) contains only the columns $2, $3 and $4, wich is desired, and so on for the other blocks.
awk -v v_i="$var_i_1" -v v_f="$var_f_1" '{ # declare variables of lower ($var_i_1) and upper ($var_f_1) bounds for first block (set of cloumns)
for (i=v_i;i<=v_f;i++) {printf (i==1?"":FS)$i}; print "" # for statement to print only comlumns between specified in v_i and v_f variables for first block
}' <a.ped_snps.temp > block_1.txt # print one txt file only with a set of columns specified in v_i and v_f variables
So, someone can help me to implement this code in a bash for? In summary, I want to use bash variables previously created in a awk command within bash for.
I hope that I was clear in my explantion.
Thanks in advance.
|
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 parses $var_i_$i as $var_i_ concatenated with $i. Since $var_i_ is likely unset/empty, v_i and v_f simply inherit the value of the loop index i.
There are ugly ways of doing the kind of indirection that you want, e.g.
$ for i in $(seq 1 3); do awk -v v_i="$(eval echo \${var_i_$i})" 'BEGIN{print v_i}'; done
23
45
67
however since bash supports arrays, a cleaner solution would be to use arrays for your var_i and var_f values, ex.
$ var_i=(23 45 67)
then (remembering that arrays are zero-indexed)
$ for i in $(seq 0 2); do awk -v v_i="${var_i[i]}" 'BEGIN{print v_i}'; done
23
45
67
| 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 relocated to file1(1st column)-"storage",
The comparison should be between 1st line of file2 and 1st line of file1. 2nd line of file2 and 2nd line of file1. Which means nth line of file2 should be compared with nth line of file1 only.
Both the files are sorted in descending order.
file1 is sorted based on descending order of column2
file2 is sorted based on descending order of column2.
file1-
Storage,Freememory
0843,282856
0867,270891
0842,232803
0868,213426
0849,188785
0844,188784
0860,169249
0855,169246
0862,169245
0853,169244
0850,112497
0857,112496
0841,112496
0839,112495
0848,112494
0851,112493
file2 -
Machine,UsedMemory
x0aaa06,111113232
x0aaa05,78851
x0aaa01,10243
x0aaa03,4099
Desired output -
x0aaa06 cannot be relocated to 0843
x0aaa05 can be relocated to 0867
x0aaa01 can be relocated to 0842
x0aaa03 can be relocated to 0868
|
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 straightforward, starting at line 2 (NR > 1) and using print instead of printf because I'm lazy.
| 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 want to have only folders with different digits, so 11, 22 and 33 should not exist. Is there a convenient for loop option to skip identical values?
Alternatively one could also create all folders and delete those with multiple values afterwards, but this seems very inefficient if there are multiple loops with many entries.
|
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 tests for arithmetic inequality. If you are looping over strings, use != instead. If the test is true ($i and $j are different), the directory is created with mkdir.
[ "$i" -ne "$j" ] && mkdir "$i$j" is a short-cut way of writing
if [ "$i" -ne "$j" ]; then
mkdir "$i$j"
fi
To delete all directories that have names like 11, 22 etc.:
for i in {1..9}; do
rmdir "$i$i"
done
This assumes that the directories are empty. Use rm -rf "$i$i" if they are not empty.
| 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 current catalogue and it's sub-catalogues but exclude the executed script itself. It's working with grep -v but now it's excluding every file that includes the name of the script (like copies of the script in the subfolders). Anyone knows how to make it work only for the executed script? I must assume someone might change the name at some point, so excluding it by hand is out of the question.
|
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
./c
./d/foo.sh
$
Alternatively, try for f in $(find . -type f | grep -v "^\./foo\.sh$"); do
| 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.txt | awk '{print $4}')
THEID=$(cat /tmp/files/extract.txt | awk '{print $2}')
extract='/tmp/files/Extracted.txt'
for i in $THEIP;
do
echo "[INFO:]Pinging IP: $i"
check=$(ping -w 1 $i)
if [ $? != 0 ] ; then
echo "[WARN:] **//sender\\** is offline"
else
echo "[INFO:] $i Pingable!"
fi
done
This is only able to get to the ping, but I am failing to print the correlating Sender to the IP. I know I am completely ignoring $THEID, that is because I have not been able to figure how to implement it.
Nested for loop - it prints out IP1 + all senders, then IP2 + all senders which defeats my purpose.
My echo should be:
[INFO:] - Sender Bob from IP 10.1.1.1 is pingable
[INFO:] - Sender Alex from IP 10.1.1.2 is pingable
and so on.
|
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; then
echo OK
else
echo NOPE
fi
done < "$input"
(bash-only version, awk might be more efficient but I'm not familiar with it)
| 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 code lists all three files listed with serial numbers 1,2,3. I want to validate if the user provides the correct input and not break the code till receiving a correct input. To do this, I have used a while loop after the above code
while [[ "$input" =~ ["$i"] ]]
do
echo "Please provide a serial number from the list given below."
files=$(ls ~/VideoExtract/*.avi)
i=1
for j in $files
do
echo "$i.$j"
file[i]=$j
i=$(( i + 1 ))
done
read -p "Enter the serial number from the above list : " input
done
This does returns the list of files again. The problem is, if I have 3 files, and if I type 4, the loop continues to work, but if I provide 5 instead, the loop breaks and moves on to the next line of the code. I am not sure if the problem is in line
while [[ "$input" =~ ["$i"] ]]
or
i=$(( i + 1 ))
Instead of =~ I have tried with != and ! $input == $i and similar other combinations, such as with and without [] for $i. Nothing seem to work.
How do I run the while loop till the time the user provides a valid input that is within the range of $i.
|
(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=(~/VideoExtract/*.avi)
quote your variables when you use them file["$i"]="$j"
let the shell control the expansion of $files when you iterate over it for j in "${files[@]}"
not strictly necessary, but indenting your code blocks will make the code far far easier to read
| 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 in this loop:
for i in $(find $parent -mindepth 1 -maxdepth 1 -type f|cut -c 11-);do
echo "this is the file: $i"
done
it is considered as multiple files :
this is the file: my_super_cool_file_2007039904_11
this is the file: (3rd
this is the file: copy).pdf
i've tried replacing the space with \space using sed 's/ /\\ /g'
but it does not seem to solve my problem, for the loop it's 3 different files, i had also the same problem using ls, and i need to stick to use find
|
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
Looping over the result of find is generally bad practice: Why is looping over find's output bad practice?
| 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 sshpass -p PASSWORDHERE ssh -o StrictHostKeyChecking=no [email protected].${i} 'hostname
echo "Checking if foo.log exists: `ls -lh /var/log/foo.log | wc -l`"
echo "Checking if bar.log is present: `ls -lh /var/log/bar.log | wc -l`"
' 2>/dev/null; echo ""; done
My script-fu is weak and I really don't have much of a clue where to start. Incidentally I want to achieve this with a basic set of tools. I'm not able to install anything third party.
Any help appreciated.
|
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 "Checking if bar.log is present: `ls -lh /var/log/bar.log | wc -l`"
' 2>/dev/null
done
That should work. Remember, ctrl + c will kill this loop if you get tired of it running during testing, or just use a smaller range to debug it, like 1 to 5.
| 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.229.131
192.168.229.132
Below is the script
#!/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.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p')
for i in 151 152
do
echo 192.168.229.\$i >> errips
done
for data in `cat errips`
do
echo data currently has $data
grep $data /etc/hosts
if [ $? -eq 0 ]
then
sed -i "s/$data/$MYIP/g" /etc/hosts
echo "completed"
unset MYIP
rm -rf errips
exit 0
fi
done
EOF
done
Below is the output
root@master:~# ./script
cat: errips: No such file or directory
successfully logged in 192.168.229.131
cat: errips: No such file or directory
successfully logged in 192.168.229.132
Why does the for loop after logging in the server is getting executed before logging in?
I tried using the below instead of 'for'
cat errips |while read line
echo line currently has $line
In this case, I found that line is still taking the IP from server file in localhost, whereas it should read it from errips file of the server i remotely logged in.
Output was
line currently has 192.168.229.131
line currently has 192.168.229.132
whereas I expected that it should read the values in file "errips" and output should be something like below
line currently has 192.168.229.151
line currently has 192.168.229.151
Now, I tried below command
cat errips |while read data
echo data currently has $data
In this case, the output was empty for the value data
data currently has
data currently has
How would I read the file "errips" in my remote server line by line, and grep for the line in /etc/hosts and then execute the if loop, which will replace the wrong ip with right ip?
|
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.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p')
for i in 151 152
do
echo 192.168.229.$i >> errips
done
for data in `cat errips`
do
echo data currently has $data
grep $data /etc/hosts
if [ $? -eq 0 ]
then
sed -i "s/$data/$MYIP/g" /etc/hosts
echo "completed"
unset MYIP
rm -rf errips
exit 0
fi
done
EOF
done
Notice the single quotes around EOF. To further illuminate, try the following:
/usr/bin/sshpass -e ssh -t -q -o StrictHostKeyChecking=no root@<your_ip> 'k=1; echo $k'
/usr/bin/sshpass -e ssh -t -q -o StrictHostKeyChecking=no root@<your_ip> "k=1; echo $k"
/usr/bin/sshpass -e ssh -t -q -o StrictHostKeyChecking=no root@<your_ip> "k=1; echo \$k"
| 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 to find all the users based on the users file and rename those users to [email protected] ? for example
owner = [email protected]
random text
random text
owner = user15
random text
random text
owner = [email protected]
i got some bits and pieces working using the ack command and the cat command but i am new to programming so i cant get a proper output. What i figured out is below but it does not really do what i need. any help is highly appreciated.
cat users | xargs -i sed 's/{}/moo/' searches
|
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 user, and then run the loop.
|
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. I'd use a different loop instead.
| 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 these large files by "year". Any suggestions?
#!/usr/awk -f
for i in *yyyymm.txt
do
# {FS = "," }
awk -F "," 'BEGIN '$1 == 2002'END{ print $0 }' $i > "$i"-2002.dat
gawk '$ 1==2002 { print $0 }' "$i" > "$i"-2002.dat
awk '/2002/' "$i" > "$i"-2002.dat
|
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 without replacement. This means that each 200 character extraction has only one chance to be selected when sampling.
Output should look like this:
>1
GAACTCTACCAAAAGGTATGTTGCTTTCACAAAAAGCTGCATTCGATCATGTGTATAATCTAGCAAAACTAGTAGGAGGAGCAAAATACCCCGAAATTGTTGCTGCTCAGGCAATGCACGAATCAAACTACCTAGATCCTAGG
ACTAATAGTGTTTATAATGCCACAAATAGAACTAATGCTTTCGGTCAAACTGGTGAC
>2
GCCTACCGCATAAAACAGCATCACCGCCACGGCTTCAGGGTATTCTCCAATGGCAAAGGCTCCCATGGTCGCGATGGACATTAAGAGAAATTCAGTAAAGAAATCTCCATTTAGAATACTTTTGAATCCTTCTTTTATCACCG
GAAAACCAACTGGGAGATAGGCCACAATGTACCAACCTACTCGCACCCAATCTGTAA
>3
GCACGTGTCACCGTCAGCATCGCGGCAGCGGAACGGGTCACCCGGATTGCTGTCGGGACCATCGTTTACGCCGTCATTGTCGTTATCGGGATCGCCCGGATTACAAATGCCGTCGCCATCGACGTCGTTACCGTCGTTCGCGG
CATCGGGGAAGCCGGCACCGGCGGCACAGTCATCGCAACCGTCGCCATCGGCATCGA
>4
GCGTTCGAAGCAATTGCACGAGACCCAAACAACGAATTGCTGGTTGTTGAACTGGAAAACTCTCTAGTCGGAATGCTTCAAATTACTTATATTCCCTACCTGACACATATTGGCAGTTGGCGTTGTCTTATAGAAGGTGTTCG
AATCCATAGTGACTATCGTGGACGAGGTTTTGGTGAGCAAATGTTCGCACATGCGAT
>5
GTTTAAGACTAACAGCAATCTGTAAGGACATAGGTGCTGGAGTTGAGGTTAGTCTGGAAGATATGATCTGGGCAGAGAAATTGTCCAAAGCAAACACCGCAGCAAGAGGTATGCTAAACACAGCAAGAAGAATAAGTAATGAT
CCTACTGATTCTTTTCTGAATGAGTTGAATATAGGAGACCCCGACTCAACTCATCAT
The input file is a ~8G file that looks like this:
CCAAGATCGCTGGTTGGCGAATCAATTTCATAAACGCCTACGCTTTCAAGGAACGTGTTAAGAATGTTCT
GGCCGAGTTCCTTATGAGACGTTTCGCGTCCCTTAAATCGAATAACGACACGAACCTTGTCGCCGTCATT
AAGAAAACCCTTTGCCTTCTTGGCCTTAATCTGAATATCACGGGTGTCCGTTACAGGTCGCAACTGGATT
TCCTTGACTTCAGAAACAGACTTACGTGAATTCTTCTTGATTTCTTTCTGACGCTTTTCATTTTCATACT
GGAACTTGCCGTAATCAATGATCTTACAAACAGGAATATCACCCTTATCAGAGATCAATACCAAATCAAG
TTCGGCATCAAAAGCGCGATCAAGTGCGTCTTCAATGTCGAGGACCGTTGTTTCTTCACCGTCAACCAAA
CGAATTGTGGAGGACTTGATGTCGTCTCGGGTACTAATTTTATTCACGTATATGTTACTCCTTATGTTGT
Any help would be appreciated. Thanks in advance.
|
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 22:38 tdHuge.txt
Paul--) ./rndSelect
inFile ./tdHuge.txt; Size 8006529300; Count 10000; Lth 200; maxIter 50; Db 1;
Iteration 1 needs 10000
Iteration 2 needs 2712
Overlap 9561: 7663038508 to 7663038657
Iteration 3 needs 728
Iteration 4 needs 195
Iteration 5 needs 50
Iteration 6 needs 11
Iteration 7 needs 2
Required 7 iterations
Reporting 10000 samples
real 2m3.326s
user 0m3.496s
sys 0m10.340s
Paul--) wc Result.txt
20000 20000 2068894 Result.txt
Paul--) head -n 8 Result.txt | cut -c 1-40
>1
5706C69636174656420696E666F726D6174696F6
>2
20737472696E672028696E207768696368206361
>3
20646F6573206E6F742067657420612068617264
>4
647320616E642073746F7265732E204966207468
Paul--) tail -n 8 Result.txt | cut -c 1-40
>9997
6F7374207369676E69666963616E7420646F7562
>9998
7472696E676F702D73747261746567793D616C67
>9999
865726520736F6D652066696C6573206D7573742
>10000
5726E65642E205768656E20746865202D66206F7
Paul--)
It requires iterations because it makes random probes into the file. If a probe overlaps an adjacent one, or a newline, then it is discarded and a smaller batch of new probes is made. With an average line length of 725 lines and a sample requirement of 200, almost 30% of probes will be too close to the end of a line to be acceptable. We don't know the average line length of the real data -- longer lines would improve the success ratio.
We also do not know whether the header lines (as noted in a previous related question of 04-Dec-2020) are still present in the file. But provided every header line is less than the sample length of 200, the header lines will be discarded (serendipity at its best).
The code is mainly GNU/awk (minimal bash) and has some comments. There is a lot of residual debug which can be hidden by setting Db=0 in the options.
#! /bin/bash
#.. Select random non-overlapping character groups from a file.
export LC_ALL="C"
#.. These are the optional values that will need to be edited.
#.. Command options could be used to set these from scripts arguments.
inFile="./tdHuge.txt"
outFile="./Result.txt"
Count=10000 #.. Number of samples.
Lth=200 #.. Length of each sample.
maxIter=50 #.. Prevents excessive attempts.
Size="$( stat -c "%s" "${inFile}" )"
Seed="$( date '+%N' )"
Db=1
#.. Extracts random non-overlapping character groups from a file.
Selector () {
local Awk='
#.. Seed the random number generation, and show the args being used.
BEGIN {
NIL = ""; NL = "\n"; SQ = "\047";
srand (Seed % PROCINFO["pid"]);
if (Db) printf ("inFile %s; Size %d; Count %d; Lth %d; maxIter %s; Db %s;\n",
inFile, Size, Count, Lth, maxIter, Db);
fmtCmd = "dd bs=%d count=1 if=%s iflag=skip_bytes skip=%d status=none";
}
#.. Constructs an array of random file offsets, replacing overlaps.
#.. Existing offsets are indexed from 1 to Count, deleting overlaps.
#.. Additions are indexed from -1 down to -N to avoid clashes.
function Offsets (N, Local, Iter, nSeek, Seek, Text, j) {
while (N > 0 && Iter < maxIter) {
++Iter;
if (Db) printf ("Iteration %3d needs %6d\n", Iter, N);
for (j = 1; j <= N; ++j) {
Seek[-j] = int ((Size - Lth) * rand());
Text[Seek[-j]] = getSample( Seek[-j], Lth);
if (Db7) printf ("Added %10d: \n", Seek[-j], Text[Seek[-j]]);
}
#.. Reindex in numeric order for overlap checking.
nSeek = asort (Seek);
if (Db7) for (j in Seek) printf ("%6d: %10d\n", j, Seek[j]);
#.. Discard offsets that overlap the next selection.
N = 0; for (j = 1; j < nSeek; ++j) {
if (Seek[j] + Lth > Seek[j+1]) {
if (Db) printf ("Overlap %6d: %10d to %10d\n",
j, Seek[j], Seek[j+1]);
++N; delete Text[Seek[j]]; delete Seek[j];
} else if (length (Text[Seek[j]]) < Lth) {
if (Db7) printf ("Short %6d: %10d\n",
j, Seek[j]);
++N; delete Text[Seek[j]]; delete Seek[j];
}
}
}
if (Iter >= maxIter) {
printf ("Failed with overlaps after %d iterations\n", Iter);
} else {
printf ("Required %d iterations\n", Iter);
Samples( nSeek, Seek, Text);
}
}
#.. Returns n bytes from the input file from position p.
function getSample (p, n, Local, cmd, tx) {
cmd = sprintf (fmtCmd, n, SQ inFile SQ, p);
if (Db7) printf ("cmd :%s:\n", cmd);
cmd | getline tx; close (cmd);
return (tx);
}
#.. Send samples to the output file.
function Samples (nSeek, Seek, Text, Local, j) {
printf ("Reporting %d samples\n", nSeek);
for (j = 1; j <= nSeek; ++j) {
printf (">%d\n%s\n", j, Text[Seek[j]]) > outFile;
}
close (outFile);
}
END { Offsets( Count); }
'
echo | awk -v Size="${Size}" -v inFile="${inFile}" \
-v outFile="${outFile}" -v Count="${Count}" -v Lth="${Lth}" \
-v maxIter="${maxIter}" \
-v Db="${Db}" -v Seed="${Seed}" -f <( printf '%s' "${Awk}" )
}
#.. Test.
time Selector
| 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 created two .txt files, stable.txt and recurring.txt, each containing a list of a subset of P_XXX that I would like to use to move the subsets to separate folders (stable and recurring, respectively). For example, P_76 and P_201 are listed in stable.txt, while P_104 and P_154 are listed in recurring.txt.
I tried a for loop to return the relevant P_XXX from the .txt file, so that I can use that to retrieve the matching .img in another for loop from the folder, which should then be moved to the stable folder:
for P in $(< stable.txt); do
for f in *"$P"*.img; do
echo mv - "$f" "./stable/$f"
done
done
It returns the correct number of P_XXX listed, but $f does not return the full filename (only the *P_XXX bit). Strangely enough, it does return the full filename for the last P_XXX in the .txt file (so ppi_noTD_d0_P_201_con_0001.img)
As there seems to be something going wrong with calling $f, I can't move the files to their respective folders (stable and recurring).
How do I solve this?
EDIT:
This is the output that I'm getting:
*.img ./stable/*P_76
*.img ./stable/*P_86
*.img ./stable/*P_89
*.img ./stable/*P_90
*.img ./stable/*P_91
*.img ./stable/*P_99
*.img ./stable/*P_121
*.img ./stable/*P_128
*.img ./stable/*P_132
*.img ./stable/*P_136
*.img ./stable/*P_140
*.img ./stable/*P_144
*.img ./stable/*P_153
*.img ./stable/*P_156
*.img ./stable/*P_162
*.img ./stable/*P_180
*.img ./stable/*P_203
*.img ./stable/*P_205
*.img ./stable/*P_208
*.img ./stable/*P_211
*.img ./stable/*P_215
*.img ./stable/*P_229
*.img ./stable/*P_250
*.img ./stable/*P_256
mv - ppi_noTD_d0_P_257con_0001.img ./stable/ppi_noTD_d0_P_257con_0001.img
|
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 first line is read by your script, the globbing expression *"$P"*.img matches nothing (unless your file names actually contain carriage return characters) and, if no nullglob (or equivalent) option is in effect, the value of f is *P_76\r*.img. When mv - "$f" "./stable/$f" is echoed, the two CR characters cause the subsequent text to be inserted at the beginning of the line, overwriting what was already there.
You can check your files for CR LF newline sequences with
$ cat -v stable.txt
P_76^M
P_201^M
or
$ od -An -c stable.txt
P _ 7 6 \r \n P _ 2 0 1 \r \n
or
$ file stable.txt
stable.txt: ASCII text, with CRLF line terminators
And you can convert them to the Unix, LF-terminated format with (among other ways):
$ dos2unix stable.txt
See also:
How to test whether a file uses CRLF or LF without modifying it?
| 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.