逐行读取名称并在Bash脚本中对其执行某个功能

时间:2014-11-24 00:39:08

标签: bash

我正在编写一个bash脚本,创建用户。 我想逐行读取一个带有名称的文本文件,并在每个文件上执行一个函数。 我已经尝试过谷歌搜索,但没有什么对我有用。 我希望用户输入文件的路径,每行一个名称,然后我将添加函数。

echo "Enter file path:"
read line
while read line
do
  name=$line
  echo "Text read from file - $name"
done < $1

我该怎么做? 我很感激你的帮助, 此致

3 个答案:

答案 0 :(得分:1)

有一些细微之处可以帮助你的脚本。在读取文件名之前,应将IFS(内部字段分隔符)设置为仅在newline上中断。这将确保您获得完整的文件名,如果它包含空格并且不加引号。在读取文件名后恢复IFS。您还需要检查$line后是否已读取read,以确保在数据中最后一行末尾没有newline的情况下获得最后一行文件。

此外,每当您从用户读取文件名时,您应该在尝试从中读取文件之前验证它是否为有效文件名:

#!/bin/bash

oifs=$IFS                               # save internal field separator
IFS=$'\n'                               # set IFS to newline (if whitespace in path/name)

echo -n "Enter file path/name: "        # suppress newline
read fname                              # read full-path/filename

IFS=$oifs                               # restore default IFS=$' \t\n'

[ -r "$fname" ] || {                    # validate input file is readable
    printf "error: invalid filename '%s'\n" "$fname"
    exit 1
}

while read line || [ -n "$line" ]       # protect against no newline for last line
do
    name=$line
    echo "Text read from file - $name"
done < "$fname"                         # double-quote fname

exit 0

样本使用/输出:

$ bash readfn.sh
Enter file path/name: dat/ecread.dat
Text read from file - read: 4163419415       0      0     4163419415   0   4395.007      0
Text read from file - read: 4163419415       0      0     4163419415   0   4395.007      0
Text read from file - read: 4163419415       0      0     4163419415   0   4395.007      1
Text read from file - read: 4163419415       0      0     4163419415   0   4395.007      0

答案 1 :(得分:0)

试试这个:

echo "Enter file path:"
read filepath
while read line
do
  name="$line"
  echo "Text read from file - $name"
done < "$filepath"

答案 2 :(得分:0)

我认为这样的事情会让你感到厌烦,试一试。

echo "Enter file path:"
read filename    
while read line    
do    
  name=$line  
  echo "Text read from file - $name"    
done < $filename