← Back to Bash Course | Chapter 9: File Testing & Filesystem | Lesson 3 of 13

Files पढ़ना

एक file पढ़ना एक किताब को एक समय में एक line पढ़ने जैसा है, इसलिए आपको कभी पूरी किताब एक साथ हाथों में रखनी नहीं पड़ती।

In this page:

  1. Reading Files
Syntax
bash
while read -r line; do
  commands using "$line"
done < file_name

cat file_name

Reading Files

आप एक पूरी file cat से पढ़ सकते हैं, या इसे line by line process कर सकते हैं while read -r line; do ... done < file से, जो बड़ी files के लिए safer है क्योंकि यह सब कुछ एक साथ memory में load नहीं करता।

read -r backslashes को escape characters के रूप में interpret होने से रोकता है। Line-by-line reading standard approach है जब हर line को individually process करना हो।

Note: हमेशा read -r (raw mode) उपयोग करें जब तक आप specifically backslash escapes interpreted न चाहें।

उदाहरण: Reading Files

bash
#!/bin/bash
printf "line one\nline two\nline three\n" > data.txt

while read -r line; do
    echo "Read: $line"
done < data.txt
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. for line in $(cat file) उपयोग करना, जो सिर्फ lines पर नहीं बल्कि spaces पर split करता है; while IFS= read -r line उपयोग करें।
  2. read में -r भूल जाना, इसलिए backslashes हटा दिए जाते हैं।
  3. एक file को $(cat file) से एक variable में पढ़ना और trailing newlines खो देना।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.