Skip to content
Fix Code Error

Read a file line by line assigning the value to a variable

March 13, 2021 by Code Error
Posted By: Anonymous

I have the following .txt file:

Marco
Paolo
Antonio

I want to read it line-by-line, and for each line I want to assign a .txt line value to a variable. Supposing my variable is $name, the flow is:

  • Read first line from file
  • Assign $name = “Marco”
  • Do some tasks with $name
  • Read second line from file
  • Assign $name = “Paolo”

Solution

The following reads a file passed as an argument line by line:

while IFS= read -r line; do
    echo "Text read from file: $line"
done < my_filename.txt

This is the standard form for reading lines from a file in a loop. Explanation:

  • IFS= (or IFS='') prevents leading/trailing whitespace from being trimmed.
  • -r prevents backslash escapes from being interpreted.

Or you can put it in a bash file helper script, example contents:

#!/bin/bash
while IFS= read -r line; do
    echo "Text read from file: $line"
done < "$1"

If the above is saved to a script with filename readfile, it can be run as follows:

chmod +x readfile
./readfile filename.txt

If the file isn’t a standard POSIX text file (= not terminated by a newline character), the loop can be modified to handle trailing partial lines:

while IFS= read -r line || [[ -n "$line" ]]; do
    echo "Text read from file: $line"
done < "$1"

Here, || [[ -n $line ]] prevents the last line from being ignored if it doesn’t end with a n (since read returns a non-zero exit code when it encounters EOF).

If the commands inside the loop also read from standard input, the file descriptor used by read can be chanced to something else (avoid the standard file descriptors), e.g.:

while IFS= read -r -u3 line; do
    echo "Text read from file: $line"
done 3< "$1"

(Non-Bash shells might not know read -u3; use read <&3 instead.)

Answered By: Anonymous

Related Articles

  • Flask and Jinja2 - Filter is…
  • Gradle error: Execution failed for task…
  • List of Timezone IDs for use with FindTimeZoneById() in C#?
  • Integrating Flow JS with Ember JS - Data not Binded
  • org.gradle.api.tasks.TaskExecutionException:…
  • Vaadin Spring Boot - There was an exception while…
  • How to sort an array in Bash
  • Does moment.js allow me to derive a timezone…
  • firebase storage java.lang.IllegalStateException:…
  • How do I split a string on a delimiter in Bash?
  • How to detect change in a property of an object in…
  • How to prevent scrolling the whole page?
  • vuejs Data property undefined
  • How do you run a command for each line of a file?
  • Adding Dynamic Input Fields With VueJs
  • How to echo with different colors in the Windows…
  • Laravel 5: Updating Multiple Records
  • Understanding component props in VueJS
  • Dynamically change bootstrap progress bar value when…
  • Form field border-radius is not working only on the…
  • "Uncaught TypeError: undefined is not a function" -…
  • Execution failed for task…
  • Removing double quotes from variables in batch file…
  • laravel vuejs/axios put request Formdata is empty
  • How to get Flow to properly work with Vue 2 (webpack)?
  • Adding a UserCreationForm to html in Django
  • How to insert data in only one type of Vector in…
  • Error: 0xC0202009 at Data Flow Task, OLE DB…
  • How to re render component once store data is…
  • Getting error "Failed to mount component: template…
  • Why does a match on covariant enum does not behave…
  • How to create a temporary table in SSIS control flow…
  • What is your most productive shortcut with Vim?
  • Aurelia - help understanding some binding behavior…
  • What are the undocumented features and limitations…
  • Echo a blank (empty) line to the console from a…
  • gnuplot : plotting data from multiple input files in…
  • A variable modified inside a while loop is not remembered
  • How do I understand how std::make_shared works?
  • Why the value of input file missing when I input the…
  • Backbone.js: Load multiple collections with one request
  • props not updating in child component after parent…
  • How can I escape white space in a bash loop list?
  • Generating a drop down list of timezones with PHP
  • Using if(isset($_POST['submit'])) to not display…
  • Vue JS - How to do conditional display of text based…
  • Lists and Components not updating after data change…
  • How do I parse command line arguments in Bash?
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Running multiple AsyncTasks at the same time -- not…
  • Shell Script Syntax Error: Unexpected End of File
  • How can I pass modelformset_factory validation in Django?
  • First echo missing when using bash -c over SSH
  • Smart way to truncate long strings
  • Backbone.js - Correct way of filtering and…
  • strange behavior with sed or xargs
  • PHP for loop Show the entries in ascending order by quantity
  • Gnuplot line types
  • Python, tkinter: Can't save with Pickle
  • Exception : AAPT2 error: check logs for details
  • Calculating a number from items in an array then…
  • Gradle: Execution failed for task ':processDebugManifest'
  • Flowtype - how to write declaration for class…
  • Django - update inline formset not updating
  • Setting the number of map tasks and reduce tasks
  • C threads corrupting each other
  • "error: assignment to expression with array type…
  • Filter the query result only and not the entire table
  • Why is Ember throwing "Uncaught Error: Assertion…
  • Backbone Sorting and Updating a listview after an action
  • Trying to embed newline in a variable in bash
  • Backbone.js Parse Method
  • Java Process with Input/Output Stream
  • Codeigniter 4 hasChanged() - I was expecting no…
  • Change the location of the ~ directory in a Windows…
  • Check if text input field is empty or includes a number
  • How to submit Polymer forms to PHP and display response
  • How do I use the nohup command without getting nohup.out?
  • polymorphic relationship in ember-data
  • Creating a search form in PHP to search a database?
  • convert assignment problem to The Maximum Flow Problem
  • Error:Execution failed for task…
  • Bash: Echoing a echo command with a variable in bash
  • Python Key Error=0 - Can't find Dict error in code
  • I'm working on pagination for my project. How do I…
  • Why is reading lines from stdin much slower in C++…
  • Why is my variable unaltered after I modify it…
  • How do I fetch host and pass from file in linux
  • linux shell script: split string, put them in an…
  • Using Computed Properties inside Methods in vueJs
  • Why is my line read not working as expected in bash?
  • Triggering text area by clicking related select/checkbox
  • Batch File: ( was unexpected at this time
  • data.table vs dplyr: can one do something well the…
  • Should ol/ul be inside or outside?
  • Invert boolean on click with v-for?
  • Running multiple async tasks and waiting for them…
  • Why cat does not work with parameter -0 in xargs?
  • C++, checking two txt files via fstream library to…
  • How to read specific characters from specific lines…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Get key by value in dictionary

Next Post:

Text editor to open big (giant, huge, large) text files

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error