在Bash中读取时如何从CSV中删除行

时间:2019-05-28 22:40:26

标签: bash readline

我目前正在这样做:

while read l
do
  echo git add $l/
  git add $l/
  # sed -i -e '1,1d' data/commit-folders.csv
  # echo git commit -am "'Autocommit'"
  # git commit -uno -am "'Autocommit'"
  # echo git push origin master
  # git push origin master
done < data/commit-folders.csv

基本上只是git add <folder>来获取CSV文件中的文件夹列表。我希望它更强大,因为每次重新启动时都会从中断处重新启动。因此,我添加了注释行,该行执行就地删​​除sed -i -e '1,1d' data/commit-folders.csv。但是,对于while read line,如果要删除它们,它将与当前行混淆。所以我想知道如何正确地做到这一点。

如何在每行上使用<path>遍历CSV文件,并在成功添加git后删除路径。似乎您需要一个循环来从文件中选择第一行,然后再从文件中删除它,而不是使用while read line

2 个答案:

答案 0 :(得分:1)

这里没有sed的解决方案。

#!/bin/bash
csv="data/commit-folders.csv"
done="$(mktemp)"

# autoremove tempfile at exit
trap 'rm "$done"' EXIT

# loop over all lines in csv
while read -r file; do
   printf "git add %s\n" "$file"
   git add "$file"

   # write processed files in tempfile
   printf "%s\n" "$file" >> "$done"

   #...
done < "$csv"

# create tempfile for merge result
newfile="$(mktemp)"

# sort: merge and sort $cvs with $done
# uniq -u: write only unique files into tempfile
sort "$csv" "$done" | uniq -u > "$newfile" 

# override $csv with tempfile
mv "$newfile" "$csv"

答案 1 :(得分:0)

您可以使用sed -i "/${l}/d",它将找到确切的行并将其删除。假设没有重复的行。

while read l
do
  echo git add $l/
  git add $l/
  # sed -i -e '1,1d' data/commit-folders.csv
  sed -i "/${l}/d" data/commit-folders.csv
  # echo git commit -am "'Autocommit'"
  # git commit -uno -am "'Autocommit'"
  # echo git push origin master
  # git push origin master
done < data/commit-folders.csv