Sysop.Fr
Catégories

apache

awk

bash

charmap

date

echo

encoding

find

grep

hexdump

irc

iso3166

ls

mysql

od

openssh

printf

python

read

sed

seq

smpp

sort/uniq

tar

tr

ucp

Articles

bash - fichiers textes au format dos (CRLF) et unix (LF)

1. Détecter le format dos (CRLF) ou unix (LF) d'un fichier texte

root@ubuntu:~# cat -ve bash_crlf.txt
line1^M$
line2
            
root@ubuntu:~# od -c bash_crlf.txt
0000000   l   i   n   e   1  \r  \n   l   i   n   e   2
0000014
            
#!/bin/bash
if od -c bash_crlf.txt |grep -q '\r'; then
    echo "file bash_crlf.txt is DOS (CRLF) format"
else
    echo "file bash_crlf.txt is UNIX (LF) format"
fi
root@ubuntu:~# ./bash_crlf.sh
file bash_crlf.txt is DOS (CRLF) format
            
#!/bin/bash
if grep -q $'\r' bash_crlf.txt; then
    echo "file bash_crlf.txt is DOS (CRLF) format"
else
    echo "file bash_crlf.txt is UNIX (LF) format"
fi
root@ubuntu:~# ./bash_crlf.sh
file bash_crlf.txt is DOS (CRLF) format
            

2. Convertir un ficher texte du format dos (CRLF) vers le format unix (LF)

root@ubuntu:~# tr -d '\r' <bash_crlf.txt >bash_lf.txt

root@ubuntu:~# cat -ve bash_lf.txt
line1$
line2

root@ubuntu:~# od -c bash_lf.txt
0000000   l   i   n   e   1  \n   l   i   n   e   2
0000013
            
#!/bin/bash
if od -c bash_lf.txt |grep -q '\r'; then
    echo "file bash_lf.txt is DOS (CRLF) format"
else
    echo "file bash_lf.txt is UNIX (LF) format"
fi
root@ubuntu:~# ./bash_crlf.sh
file bash_lf.txt is UNIX (LF) format
            
#!/bin/bash
if grep -q $'\r' bash_lf.txt; then
    echo "file bash_lf.txt is DOS (CRLF) format"
else
    echo "file bash_lf.txt is UNIX (LF) format"
fi
root@ubuntu:~# ./bash_crlf.sh
file bash_lf.txt is UNIX (LF) format