BASH grep 的输出

BASH output from grep

我对 bash 比较陌生,我正在针对第一种情况测试我的代码。

counter=1
for file in not_processed/*.txt; do
  if [ $counter -le 1 ]; then
    grep -v '2018-07' $file > bis.txt;
    counter=$(($counter+1));
  fi;
done

我想从我的文件中减去所有包含“2018-07”的行。新文件需要命名为 $file_bis.txt。

谢谢

我不明白为什么您要针对这个简单的要求使用计数器和 if 条件。使用下面的脚本来满足您的要求:-

#first store all the files in a variable
files=$(ls /your/path/*.txt)
# now use a for loop
for file in $files;
do
  grep '2018-07' $file >> bis.txt
done

这里最好避免 for 循环,因为下面单行就足够了

grep -h '2018-07' /your/path/*.txt >  bis.txt

使用 sedawk 可以更轻松、更快速地处理复杂文件。

sed -n '/2018-07/p' not_processed/*.txt

然后您会在控制台中获得输出。如果需要,可以将输出通过管道传输到新文件。

sed -n '/2018-07/p' not_processed/*.txt >> out.txt

这是对 not_processed/*.txt

中的所有文件执行此操作
for file in not_processed/*.txt
do
  grep -v '2018-07' $file > "$file"_bis.txt
done

这是只对 not_processed/*.txt

中的前 2 个文件执行此操作
for file in $(ls not_processed/*.txt|head -2)
do
  grep -v '2018-07' $file > "$file"_bis.txt
done

不要忘记在 $file 上添加 "",否则 bash 会将 $file_bis 视为一个没有赋值的新变量。