2

I want to convert .tbl files to .csv in /data/ directory which I've got read-only access. I'm using this command:

for i in `ls *.tbl`; do
    sed 's/|$//' $i > ${i/tbl/csv}
    echo $i
done

But I'm getting:

-bash: supplier.csv: Permission denied

And I don't know how to change the script such that it could save the output in a writable directory. Any idea how to solve it?

wjandrea
  • 14,236
  • 4
  • 48
  • 98

2 Answers2

4

Just specify a different path:

for tbl in *.tbl ; do
    sed 's/|$//' "$tbl" > /another/path/"${tbl%.tbl}".csv
    echo "$tbl"
done

Few minor fixes:

  1. Don't parse the output of ls, just iterate over an expanded wildcard pattern.

  2. Double quote variables (filenames can contain whitespace).

  3. I used Remove Matching Suffix instead of Substitution.

choroba
  • 9,643
4

Just specify the path (here /path/to/writable/dir/) before the filename:

for i in *.tbl; do
  sed 's/|$//' "$i" >"/path/to/writable/dir/${i/%tbl/csv}"
  echo "$i"
done

You should never parse the output of ls (Why?) and always quote variables like $i here. Adding % at the pattern’s beginning makes it match against the end of the string so that a filename like tbl.tbl becomes tbl.csv rather than csv.tbl. Read more about Parameter expansion here on bash-hackers.org.

dessert
  • 39,982