175 lines
2.0 KiB
Markdown
175 lines
2.0 KiB
Markdown
# Lire un fichier
|
|
|
|
|
|
|
|
```bash
|
|
$ cat test.txt
|
|
ubuntu Linux
|
|
mint Linux
|
|
debian Linux
|
|
raspbian Linux
|
|
mojave macOS
|
|
sierra macOS
|
|
tiger macOS
|
|
snowleopard macOS
|
|
```
|
|
|
|
|
|
|
|
#### Lire un fichier:
|
|
|
|
```bash
|
|
$ 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é:
|
|
|
|
```bash
|
|
$ 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:
|
|
|
|
```bash
|
|
$ 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:
|
|
|
|
```bash
|
|
$ 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:
|
|
|
|
```bash
|
|
$ cat read.sh
|
|
|
|
# !/bin/bash
|
|
OLDIFS=$IFS
|
|
IFS=","
|
|
while read f1 f2
|
|
do
|
|
echo "Distrib : $f1"
|
|
echo "OS : $f2"
|
|
done < test.csv
|
|
IFS=$OLDIFS
|
|
```
|
|
|
|
```bash
|
|
$ cat read.sh
|
|
|
|
# !/bin/bash
|
|
while IFS="," read f1 f2 f3
|
|
do
|
|
echo "Distrib : $f1"
|
|
echo "OS : $f2"
|
|
done < test.csv
|
|
```
|
|
|
|
|
|
|
|
Multiples séparateurs:
|
|
|
|
```bash
|
|
IFS=":/"
|
|
```
|
|
|