简体   繁体   English

如何使用bash脚本修改多个文件

[英]How to modify multiple files using a bash script

I have a file called script.sh with the following code: 我有一个名为script.sh的文件,其中包含以下代码:

#!/bin/bash

file=list.txt
IFS=$','
cat $file 
for i in `cat $file`
do
    echo "The name of the file I am going edit is $i"
    awk 'BEGIN{FS=OFS=","} /^\<AA_xx\>/||/^\<AA\>/{$160="CC,0,DD,0"} 1' $i \
        > temp_file.csv && mv temp_file.csv $i
done

list.txt contains the path to a .csv file, eg, /ws/user/stack.csv . list.txt包含.csv文件的路径,例如/ws/user/stack.csv

However, I would like to modify this script to read all the files I specify in list.txt , ie, my list.txt contains 但是,我想修改此脚本以读取我在list.txt指定的所有文件,即,我的list.txt包含

/ws/user/stack.csv
/ws/user/stack1.csv
/ws/user/stack2.csv

I want the script to use this awk in each file mentioned in list.txt . 我希望脚本在list.txt提到的每个文件中使用此awk。

Can you help me with this? 你能帮我吗?

The following does the trick 以下是技巧

script.sh script.sh

#!/bin/bash
while read -r line; do
    cat "$line" | awk '{print $0}' > "output_$line"
done < "$1"

Then you just call it with 然后你用

$ ./script.sh list.txt

If you have a large awk code, I recommend organizing it in a function. 如果您的awk代码很大,建议您将其组织在一个函数中。

script.sh script.sh

#!/bin/bash
yourAwkFunction(){
    awk '{print $0}'
}

while read -r line; do
    cat "$line" | yourAwkFunction > "output_$line"
done < "$1"

line is the variable that receives the value of each line of list.txt . line是接收list.txt每行值的变量。 This means that line is /ws/user/stack.csv for the first iteration and then /ws/user/stack.csv1 for the second and so on. 这意味着对于第一次迭代,该line/ws/user/stack.csv ,对于第二次迭代,则是/ws/user/stack.csv1 ,依此类推。

For more on reading lines of files, you may check http://mywiki.wooledge.org/BashFAQ/001 有关读取文件行的​​更多信息,请访问http://mywiki.wooledge.org/BashFAQ/001。

Since your comment says list.txt is newline separated, just follow how to read a file line by line here: Read a file line by line assigning the value to a variable 由于您的评论说list.txt是换行符,因此请按照此处逐行读取文件的方式进行操作:逐行读取文件,将值分配给变量

Which would give you: 这会给你:

#!/bin/bash

while IFS='' read -r file || [[ -n "$file" ]]; do
  echo "The name of the file I am going edit is $file"
  awk 'BEGIN{FS=OFS=","} /^\<AA_xx\>/||/^\<AA\>/{$160="CC,0,DD,0"} 1' $file \
    > temp_file.csv && mv temp_file.csv $file
done < list.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM