Extract values based on parameters passing in arguments

Based on arguments passing in command prompt values should fetch and store in new file.

Sample:-

sh test.sh 10 30 35 45

cat test.sh
..

cut -c $1-$2,$3-$4 file_name >> file_new
...
...

Above sample passing 4 arguments.. but it may differ (sh test.sh 10 30 35 45 70 75 ) based on arguments to fetch without changing scripts.

Making lots of wild assumptions about what operating system (and, therefore what type of shell is installed as sh , one might try something like the following:

#!/bin/sh
IAm=${0##*/}

if [ $# -lt 2 ]
then	printf 'Usage: %s low high [low high]...\n' "$IAm" >&2
	exit 1
fi
list=$1-$2
shift 2
while [ $# -ge 2 ]
do	list=$list,$1-$2
	shift 2
done
cut -c "$list" file_name >> file_new

Obviously, you should add a check to verify that an odd number of arguments were not given and you might want to add an output pathname as a parameter instead of always appending to the file named file_new , but this should get you started.

1 Like