0

I have a file called Year.txt

Year2000= 1/2/3/4/
Year2001= 5/6/7/8/
Year2002= 9/10/11/12/
....
....
....
Year2020= 100/101/102/

etc and so on

I need to take this Year.txt as reference in my another script some sample.sh

sample.sh

source /home/user/Year.txt
d=cp $filename $1
echo $d

sample.sh Year2000(passing Year2000 as first argument)

**I need to cut the second part after = if I pass Year2000 as my argument and paste this 1/2/3/4/ in my statement

**I need to cut the second part after = if I pass Year2001 as my argument and paste this 5/6/7/8/ in my copy statement etc..

I need output like this:

Input1 sample.sh Year2000

Output: cp somefile.txt 1/2/3/4/

Input2: sample.sh Year2001

Output: cp somefile.txt 5/6/7/8/

In Short -- I need to take the reference from another file and generate the copy statement

6
  • Does your input file really have spaces after the =? If so, it's not a legal bash assignment, so you can't source it. Commented May 1, 2019 at 19:39
  • Which shell are you targeting? Does it really need to be /bin/sh, or can you use bash? (Associative arrays are a very good fit for the problem at hand). Since source isn't a legal POSIX sh statement, it sounds likely you're already testing on bash anyhow. Commented May 1, 2019 at 19:41
  • We can change the input file with any delimiter, | , double quotes anything . but I need copy statement should be ready . It is not mandate to use = Commented May 1, 2019 at 19:41
  • echo $0 -bash . Doesn't matter . Commented May 1, 2019 at 19:43
  • It does matter. Bash disables features if you run it under the name sh; it must be invoked as bash for the full extended language to be available. Commented May 1, 2019 at 19:44

1 Answer 1

1

Don't source files that aren't legal bash code. In this case, an associative array lets you store as many key/value pairs as you need inside a single variable.

#!/usr/bin/env bash
case $BASH_VERSION in ''|[123].*) echo "ERROR: Needs bash 4.0 or newer" >&2; exit 1;; esac

year_name=$1
file_name=$2

[[ $file_name ]] || { echo "Usage: $0 year-name file-name" >&2; exit 1; }

# Read year.txt, and generate a map
declare -A dirs_by_year=( )
while IFS='= ' read -r k v; do
  dirs_by_year[$k]=$v
done <Year.txt

if ! [[ ${dirs_by_year[$year_name]} ]]; then
  echo "ERROR: User specified year $1, but input file does not have a directory for it" >&2
  echo "       ...defined years follow:" >&2
  declare -p dirs_by_year >&2  # print array definition to show what we read
  exit 1
fi

# generate and write a cp command
printf '%q ' cp "$file_name" "${dirs_by_year[$year_name]}"
Sign up to request clarification or add additional context in comments.

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.