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"
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:
For proper error handling:
Using the following Bash template should allow you to read one value at a time from a file and process it.
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:
Then call it like:
The following (save as
rr.sh
) reads a file passed as an argument line by line:Explanation:
IFS=''
(orIFS=
) 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
(sinceread
returns a non-zero exit code when it encounters EOF).Run the script as follows:
....