Read a file line by line assigning the value to a

2018-12-31 03:05发布

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"

标签: bash
9条回答
弹指情弦暗扣
2楼-- · 2018-12-31 03:24
#! /bin/bash
cat filename | while read LINE; do
    echo $LINE
done
查看更多
看淡一切
3楼-- · 2018-12-31 03:26

Many people have posted a solution that's over-optimized. I don't think it is incorrect, but I humbly think that a less optimized solution will be desirable to permit everyone to easily understand how is this working. Here is my proposal:

#!/bin/bash
#
# This program reads lines from a file.
#

end_of_file=0
while [[ $end_of_file == 0 ]]; do
  read -r line
  # the last exit status is the 
  # flag of the end of file
  end_of_file=$?
  echo $line
done < "$1"
查看更多
余生无你
4楼-- · 2018-12-31 03:31

For proper error handling:

#!/bin/bash

set -Ee    
trap "echo error" EXIT    
test -e ${FILENAME} || exit
while read -r line
do
    echo ${line}
done < ${FILENAME}
查看更多
与君花间醉酒
5楼-- · 2018-12-31 03:33

Using the following Bash template should allow you to read one value at a time from a file and process it.

while read name; do
    # Do what you want to $name
done < filename
查看更多
荒废的爱情
6楼-- · 2018-12-31 03:35

I read the question as:

"if I want read a file using expect how should I do? I want do that because when I wrote 'doing some tasks with $name', I meant that my tasks are expect commands."

Read the file from within expect itself:

yourExpectScript:

#!/usr/bin/expect
# Pass in filename from command line

set filename [ lindex $argv 0 ]

# Assumption: file in the same directory

set inFile [ open $filename r ]

while { ! [ eof $inFile ] } {

    set line [ gets $inFile ]

    # You could set name directly.

    set name $line

    # Do other expect stuff with $name ...

    puts " Name: $name"
}

close $inFile

Then call it like:

yourExpectScript file_with_names.txt
查看更多
君临天下
7楼-- · 2018-12-31 03:36

The following (save as rr.sh) reads a file passed as an argument line by line:

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

Explanation:

  • IFS='' (or IFS=) prevents leading/trailing whitespace from being trimmed.
  • -r prevents backslash escapes from being interpreted.
  • || [[ -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).

Run the script as follows:

chmod +x rr.sh
./rr.sh filename.txt

....

查看更多
登录 后发表回答