how to avoid escape letters in reading text file

43 Views Asked by At

I'm reading a CSV file separated by ';'. As basic example consider this "file.csv":

a1;a2;/unixpath/file1;a4
b1;b2;\winpath\file2;b4

Some fields contain windows path, and so use the backslash and are unquoted.

I'm using this bash script:

#!/bin/bash
fileIn="file.csv"
IFS=';'
while read -a lineV ; do
   #echo "lineV: '${lineV[@]}'"
   for ((c=0; c<=3; c++)); do
      field="${lineV[$c]}"
      echo -E "c:$c field:'$field' '${lineV[$c]}'"
   done
   echo "---"
done < $fileIn

The output always skip backslash as so:

c:0 field:'a1' 'a1'
c:1 field:'a2' 'a2'
c:2 field:'/unixpath/file1' '/unixpath/file1'
c:3 field:'a4' 'a4'
---
c:0 field:'b1' 'b1'
c:1 field:'b2' 'b2'
c:2 field:'winpathfile2' 'winpathfile2'
c:3 field:'b4' 'b4'
---

I tryed adding quotes but same results. I added -E to echo, same results.

How can I read backslash as literal '\' ?

2

There are 2 best solutions below

0
Gilles Quénot On

Use -r switch:

while IFS=';' read -r -a lineV ; do

for hardening the use of this while loop.

That yields:

c:0 field:'a1' 'a1'
c:1 field:'a2' 'a2'
c:2 field:'/unixpath/file1' '/unixpath/file1'
c:3 field:'a4' 'a4'
---
c:0 field:'b1' 'b1'
c:1 field:'b2' 'b2'
c:2 field:'\winpath\file2' '\winpath\file2'
c:3 field:'b4' 'b4'
---

help read:

-r do not allow backslashes to escape any characters


See bash FAQ#1

1
Valerio On

found. Using:

while read -ra lineV ; do

will avoid interpreting backslash