Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
928 views
in Technique[技术] by (71.8m points)

conda - Get the kth field of a txt file by lines in bash

My txt file is of this structre:

# packages in environment at /scratch/hello/anaconda3:
#
# Name                    Version                   Build  Channel
_ipyw_jlab_nb_ext_conf    0.1.0                    py37_0
absl-py                   0.7.1                    pypi_0    pypi
alabaster                 0.7.12                   py37_0
anaconda-client           1.7.2                    py37_0
anaconda-navigator        1.9.7                    py37_0
anaconda-project          0.8.2                    py37_0
annoy                     1.14.0                   pypi_0    pypi

I would like to conda install all the packages listed in this txt file, with version specified.

My idea is to for loop over all lines (starting from the 4th line), get the value from the first and second field, and save them into PACKAGE and VERSION, and install the package by calling conda install $PACKAGE=$VERSION (for example, conda install pandas=0.20.3

I would like to write a shell script to do this. I have written a demo file just to read the ith line and it's second field:

#!/bin/bash
LINES=$(wc -l < conda_env.txt)
for i in {4...10}
do
awk -F '|' 'NR==${i}{print $2}' conda_env.txt
done

and it gives me error: awk: bailing out at source line 1.

question from:https://stackoverflow.com/questions/65911763/get-the-kth-field-of-a-txt-file-by-lines-in-bash

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Would you please try the following:

#!/bin/bash

while read -r package version _; do
    [[ $package = "#"* ]] && continue           # skip the comment lines
    # remove "echo" if the output looks good
    echo conda install "$package=$version"
done < "conda_env.txt"

Output:

conda install _ipyw_jlab_nb_ext_conf=0.1.0
conda install absl-py=0.7.1
conda install alabaster=0.7.12
conda install anaconda-client=1.7.2
conda install anaconda-navigator=1.9.7
conda install anaconda-project=0.8.2
conda install annoy=1.14.0

If the output lines meet your expectations, then remove echo and execute the script.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...