Peter71 Peter71 - 5 months ago 25
Bash Question

terminal command: handle special characters in filename

I want to execute some commands in terminal. I create them in Swift 3.0 and write them to a command file. But some special characters make problems, e.g. single quote:

mv 'Don't do it.txt' 'Don_t do it.txt'

I use single quote to cover other special characters. But what's about single quotes itself. How can I convert them in a way every possible filename can be handled correctly?


You question is strange:

  1. In this case we would be writing to shell script rather than a text file

  2. You are replacing single quotes in the output file name, but not spaces, which should be replaced

Here is a solution that gives proper escaping for the input files, and proper replacing (read: spaces too) for the output files:

#!/usr/bin/awk -f
  mi = "\47"
  no = "[^[:alnum:]%+,./:=@_-]"
  print "#!/bin/sh"
  while (++os < ARGC) {
    pa = split(ARGV[os], qu, mi)
    printf "mv "
    for (ro in qu) {
      printf "%s", match(qu[ro], no) ? mi qu[ro] mi : qu[ro]
      if (ro < pa) printf "\\" mi
    gsub(no, "_", ARGV[os])
    print FS ARGV[os]


mv 'dont do it!.txt' dont_do_it_.txt
mv Don\''t do it.txt' Don_t_do_it.txt
mv dont-do-it.txt dont-do-it.txt