2

I've been trying all the morning thinking how to do what I want to do but... I am starting to feel desperate!

I have an array of rows and columns in a .txt file. So I want to create a script that gives to me this information:

If I type it to the terminal (script.sh 1 2 3), it should give me columns 1 to 3 from the .txt file.

If I type it to the terminal (script.sh), it should give me column 5 to the last column.

If I type it to the terminal (script.sh 1 2 3 -g insulin), it should give me columns 1 to 3 of the rows that contain the word "insulin". The -g here means "gene", so the aim is to look for that gene.

I've written a code that gives me the columns I want or all the columns if I don't introduce any variable, but I can't go ahead with the -g and gene variables... Do you have any idea?

Here's my code:

#!/bin/bash

var="$(echo $@ | tr " " ",")"

if [ $# = 0 ]; then
awk '{for (x=5; x<=NF; x++) {printf "%s ", $x } printf "\n" }' affy.txt
else
cat affy.txt | cut -d" " -f$var
fi

Thank you!

2 Answers 2

2

script.sh:

#!/bin/bash
columns=""
word="."
for arg; do
    if [[ $arg == "-g" ]]; then
        shift
        word=$1
    else
        columns+="$1,"
    fi
    shift
done
if [[ $columns ]]; then
    columns=${columns%,}
else
    columns="5-"
fi
grep $word affy.txt | cut -d " " -f "$columns"
Sign up to request clarification or add additional context in comments.

1 Comment

nice use of shift to parse the args
0

You want your awk script to know about the search string from -g. To pass values into a script, I have had good success with the -v argument of gawk. Once you have the argument of -g in your script in variable lookfor (e.g., using getopt), run:

 gawk -v searchtext="$lookfor" -- '$0 ~ searchtext { print $1, $2, $3 }'

The -v argument makes searchtext refer to $lookfor, i.e., the argument to -g in the bash script. Then $0 ~ searchtext selects any line where the search text is anywhere on the line. For matching lines, the first three fields are printed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.