0

I am trying to make a script that will allow me to read all files in a directory line by line while doing a command to a specific column of these files. The files that I am dealing with are .txt files that have values that are separated by commas. I am able to execute the code with a single file by inputting the text file to the script and then outputting the values but not with multiple files, which is my goal. I would like the files to be read in the order they are in in the directory. Here is what I have so far.

directory=$(/dos2unix/*.txt)
file=$(*.txt")
IFS=","
for "$file" in "$directory";
do
    while read -ra line;
    do
            if [ "${line[1]}" != "" ]; then
                echo -n "${line[*]}, Hash Value:"; echo "${line[1]}" | openssl dgst -sha1 | sed 's/^.* //'
            else
                if [ "${line[1]}" == "" ]; then
                    echo "${line[*]}, Hash Value:None";
                fi
            fi
    done
done

Some of the errors that I am getting are:

$ ./orange2.sh
/dos2unix/test1.txt: line 1: hello: command not found
/dos2unix/test1.txt: line 2: goodbye: command not found
/dos2unix/test1.txt: line 4: last: command not found
./orange2.sh: line 28: unexpected EOF while looking for matching `"'
./orange2.sh: line 33: syntax error: unexpected end of file

Any tips, suggestions, or examples?

Thanks all

UPDATE

I am also looking to copy all of the files eventually to contain the command that you see in the first if statement so I would like to a.) keep my files separate and b.) create a copy that will contain the updated value.

4

1 回答 1

0

如果要将文件名保存在变量中,请使用array=(a b c)语法创建数组。没有美元符号。然后用 循环遍历数组for item in "${array[@]}"

while read要使用循环读取文件,请使用while read; do ...; done < "$file". 它看起来很奇怪,但文件被重定向到整个循环中。

files=(/dos2unix/*.txt)

for file in "${files[@]}"; do
    while IFS=',' read -ra line; do
        ...
    done < "$file"
done

另一种方法是使用cat将所有文件连接在一起,这样您就可以摆脱外部for循环。

cat /dos2unix/*.txt | while IFS=',' read -ra line; do
    ...
done
于 2013-08-19T17:23:49.073 回答