Lire un fichier¶
$ cat test.txt
ubuntu Linux
mint Linux
debian Linux
raspbian Linux
mojave macOS
sierra macOS
tiger macOS
snowleopard macOS
Lire un fichier:¶
$ cat read.sh
#!/bin/bash
while read line
do
echo "Line is : $line"
done < test.txt
$ ./read.sh
Line is : ubuntu Linux
Line is : mint Linux
Line is : debian Linux
Line is : raspbian Linux
Line is : mojave macOS
Line is : sierra macOS
Line is : tiger macOS
Line is : snowleopard macOS
Lire un fichier tabulé:¶
$ cat read.sh
#!/bin/bash
while read f1 f2
do
echo "Distrib : $f1"
echo "OS : $f2"
done < test.txt
$ ./read.sh
Distrib : ubuntu
OS : Linux
Distrib : mint
OS : Linux
Distrib : debian
OS : Linux
Distrib : raspbian
OS : Linux
Distrib : mojave
OS : macOS
Distrib : sierra
OS : macOS
Distrib : tiger
OS : macOS
Distrib : snowleopard
OS : macOS
Changer le séparateur:¶
$ cat read.sh
#!/bin/bash
while read f1 f2
do
echo $f1:$f2
done < test.txt > test2.txt
$ cat test2.txt
ubuntu:Linux
mint:Linux
debian:Linux
raspbian:Linux
mojave:macOS
sierra:macOS
tiger:macOS
snowleopard:macOS
Lire un fichier .csv:
$ cat test.csv
ubuntu,Linux
mint,Linux
debian,Linux
raspbian,Linux
mojave,macOS
sierra,macOS
tiger,macOS
snowleopard,macOS
$ cat read.sh
# !/bin/bash
IFS=","
while read f1 f2
do
echo "Distrib : $f1"
echo "OS : $f2"
done < test.csv
$ ./read.sh
Distrib : ubuntu
OS : Linux
Distrib : mint
OS : Linux
Distrib : debian
OS : Linux
Distrib : raspbian
OS : Linux
Distrib : mojave
OS : macOS
Distrib : sierra
OS : macOS
Distrib : tiger
OS : macOS
Distrib : snowleopard
OS : macOS
Ne pas changer le séparateur définitivement:
$ cat read.sh
# !/bin/bash
OLDIFS=$IFS
IFS=","
while read f1 f2
do
echo "Distrib : $f1"
echo "OS : $f2"
done < test.csv
IFS=$OLDIFS
$ cat read.sh
# !/bin/bash
while IFS="," read f1 f2 f3
do
echo "Distrib : $f1"
echo "OS : $f2"
done < test.csv
Multiples séparateurs:
IFS=":/"
Dernière mise à jour:
March 15, 2019