4
\$\begingroup\$

I have a script for school that mimics the cp command. Part of the assignment is to modify the script so that the while loop (that assigns stdin to the variable filelist) is instead done with sed.

The last argument needs to be saved to the variable to because that could be a directory depending on other user input in the script.

while [ "$#" -gt 1 ]
do
        filelist="$filelist $1"
        shift
done

to="$1"

Is this finished product good? How could I polish it up?

filelist=$(echo $* | sed 's/ [^ ]*$//')
to=$(echo $* | sed 's/^.* \([^ ]*\)$/\1/')
\$\endgroup\$
  • \$\begingroup\$ The while loop produces different output, " 1 2 3" vs. "1 2 3" by the sed call. \$\endgroup\$ – ferada Dec 5 '14 at 13:52
  • \$\begingroup\$ The sed version assumes each argument is only one "word". If the last argument has spaces in it your version fails. (To be fair though I don't know that with sed you can do better than that easily and robustly.) \$\endgroup\$ – Etan Reisner Dec 5 '14 at 16:36
  • 1
    \$\begingroup\$ Also there's no reason to use sed for the to assignment. len=$#; to=${!len} or len=$#; a=("$@"); to=${a[$# - 1]}. \$\endgroup\$ – Etan Reisner Dec 5 '14 at 16:39
2
\$\begingroup\$
filelist="$(
   IFS='
'
   echo "$*" | sed -n '$!H;${x;s/.//;s/\n/ /g;p;}'
   )"

to="$(
   IFS='
'
   echo "$*" | sed '$!d'
   )"

This should do, assuming there are no new lines in the parameter/s.

Your code assume there is only 1 word per argument. This have nearly no impact unless the last argument is a multi word (miss interpreted by your code taking the very last word and not argument).

For this reason:

  • Use another separator than standard white space/tab for passing the parameter to sed.
    • Use $* (and not $@) to have the shell separation on argument and not word.
    • Using IFS Internal Field Separator of the shell.
    • Using a sub shell to limit IFS scope to this function (hopefully already the case with "$(...)" used for assignation.
  • Adapt sed to separate argument with new line, and readapt the new line to white space for final value (sed by default work per line so need to load the lines in buffer before working on it at the end).
\$\endgroup\$
  • \$\begingroup\$ sorry missing this part, i will adapt the post \$\endgroup\$ – NeronLeVelu Jul 28 '15 at 7:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.