0

Attempting to parse through a file

Contents of file: Directory|days|recursive|delete_directory|prefix|logfile

/testing/bash/folder1|7|Y|N||
/testing/bash/folder2|8|Y|Y||

The script written is below:

#/bin/bash

parameters=${1}
param_array=()

IFS='|'
for parameter in ${parameters}
do
        param_array+=(parameter)
done
IFS=${OIFS}

dir_name=${param_array[0]}
days_old=${param_array[1]}
recursive=${param_array[2]}
delete_dir=${param_array[3]}
prefix=${param_array[4]}
log_file=${param_array[5]}

echo ${dir_name}
echo ${days_old}
echo ${recursive}
echo ${delete_dir}
echo ${prefix}
echo ${log_file}

The script posts the results below:

./parameters trim_dir.dat
parameter

The desired results are below:

/testing/bash/folder1
7
Y
N
 

/testing/bash/folder2
8
Y
Y
  • Please consider making your own life much easier by writing a single line at a time and testing that it works before proceding, instead of writing the whole script and then trying to debug all the problems at the same time. For starters, you don't open or read from the file at any point. See [this post](https://stackoverflow.com/questions/10929453/read-a-file-line-by-line-assigning-the-value-to-a-variable) for how to read a file line by line in bash – that other guy Aug 11 '20 at 20:14
  • The line `/testing/bash/folder1|7|Y|N||` has 5 fields whereas your format has 6 fields. – M. Nejat Aydin Aug 11 '20 at 20:19
  • 1
    Additionally, you don't need a `for` loop. Simply use `IFS=\| read -ra param_array <<< "$parameters"`, thus you don't need to restore the `IFS` either. – M. Nejat Aydin Aug 11 '20 at 20:23
  • 2
    Extending @M.NejatAydin's comment: if you want to read from a file (specified by `$1`), use `while IFS=\| read -ra param_array; do ... done <"$1"`, or maybe skip the array and use `while IFS=\| read -r dir_name days_old recursive delete_dir prefix log_file; do ... done <"$1"` – Gordon Davisson Aug 11 '20 at 20:33
  • @M.NejatAydin, no that's 6 fields, the last 2 are empty. – glenn jackman Aug 11 '20 at 20:38
  • 1
    @glennjackman `IFS=\| read -a arr <<< '/testing/bash/folder1|7|Y|N||'; echo ${#arr[*]}` prints `5`. `IFS` is used as a field terminator, not a field separator, in bash. – M. Nejat Aydin Aug 11 '20 at 20:45
  • Thanks for the clarification. It's still odd though: with `IFS='|' read -ra x <<<"a|b|c"` we get 3 fields even though the last field is not terminated. – glenn jackman Aug 11 '20 at 21:46
  • @glennjackman This behaviour of `IFS` is strange in itself. It is explained [here](https://mywiki.wooledge.org/BashPitfalls#IFS.3D.2C_read_-ra_fields_.3C.3C.3C_.22.24csv_line.22) as historical reasons. – M. Nejat Aydin Aug 11 '20 at 22:05

0 Answers0